The Strategy and Observer Design Patterns

By Published 8 min read

The Strategy and Observer Design Patterns

Introduction:

In the last Low Level Design lesson we learned Dependency Injection: instead of creating its own helpers, a class receives them from outside. Today we will look at two classic design patterns that build on the same idea. If you are new to design patterns, start with What is Design Pattern? first.

  • The Strategy pattern lets you swap one piece of behaviour (how to calculate shipping, how to sort, how to pay) without changing the code that uses it.
  • The Observer pattern lets many parts of your app react when something happens (an order is placed, a user signs up), without the code that raised the event knowing who is listening.

Both are behavioural patterns from the famous “Gang of Four” book, and you have almost certainly used them already without knowing their names. Every example below is plain JavaScript, and it was run with Node.js. The outputs in the comments are real.

Part 1: The Strategy Pattern

1. The problem:

Imagine an online shop. The shipping cost depends on the method the customer picks:

function shippingCost(method, weightKg) {
  if (method === "standard") return 40 + 10 * weightKg;
  if (method === "express") return 100 + 20 * weightKg;
  if (method === "pickup") return 0;
  throw new Error(`Unknown method: ${method}`);
}

console.log(shippingCost("express", 2)); // 140

This looks fine with three methods. But the business keeps asking for more: same-day delivery, free shipping above ₹999, a special rate for one city. Each new rule means opening this function again, adding another if, and risking breaking the methods that already work. The function also knows about every method, so it keeps growing forever.

This breaks the Open/Closed principle from SOLID: code should be open for extension, but closed for modification.

2. The idea:

The Strategy pattern says: put each version of the behaviour in its own object, give them all the same method, and let the main code use whichever one it is given.

There are three parts:

  • Strategy: the shared shape, here “an object with a cost(weightKg) method”.
  • Concrete strategies: one class per way of doing it.
  • Context: the class that uses a strategy without knowing which one it is.

3. The code:

class StandardShipping {
  cost(weightKg) { return 40 + 10 * weightKg; }
}
class ExpressShipping {
  cost(weightKg) { return 100 + 20 * weightKg; }
}
class StorePickup {
  cost() { return 0; }
}

class Checkout {
  constructor(shippingStrategy) {
    this.shipping = shippingStrategy;
  }
  setShipping(shippingStrategy) {
    this.shipping = shippingStrategy;
  }
  total(itemsTotal, weightKg) {
    return itemsTotal + this.shipping.cost(weightKg, itemsTotal);
  }
}

const checkout = new Checkout(new StandardShipping());
console.log(checkout.total(500, 2)); // 560

checkout.setShipping(new ExpressShipping());
console.log(checkout.total(500, 2)); // 640

checkout.setShipping(new StorePickup());
console.log(checkout.total(500, 2)); // 500

Checkout has no if at all. It only knows that the strategy has a cost method. It also passes the order total, in case a strategy needs it (the ones above simply ignore it). The customer can switch methods at runtime, and we just call setShipping.

Notice that the strategy is passed into the constructor. That is the Dependency Injection we learned in the last lesson. The two ideas work very well together.

4. Adding a new strategy:

Now the business wants free shipping on orders of ₹999 or more. We add a new class and do not touch the existing ones:

class FreeAboveThreshold {
  constructor(base, threshold) {
    this.base = base;
    this.threshold = threshold;
  }
  cost(weightKg, itemsTotal) {
    return itemsTotal >= this.threshold ? 0 : this.base.cost(weightKg);
  }
}

This strategy uses the order total that Checkout already passes in. Checkout itself did not change at all:

const checkout2 = new Checkout(new FreeAboveThreshold(new StandardShipping(), 999));
console.log(checkout2.total(500, 2), checkout2.total(1200, 2)); // 560 1200

The new strategy even wraps an existing one, so “free above ₹999, otherwise standard” took only a few lines.

5. Strategies as plain functions:

In JavaScript, functions are values, so a strategy does not have to be a class. For small rules, an object of functions is often the cleanest version of the pattern:

const discounts = {
  none: (total) => total,
  festive: (total) => total * 0.9,
  flat100: (total) => Math.max(0, total - 100),
};

function applyDiscount(total, code) {
  const strategy = discounts[code] ?? discounts.none;
  return strategy(total);
}

console.log(applyDiscount(1000, "festive"));  // 900
console.log(applyDiscount(1000, "flat100"));  // 900
console.log(applyDiscount(1000, "oops"));     // 1000

You already use this pattern every time you pass a compare function to array.sort((a, b) => a - b). The sort algorithm stays the same, and you hand it the strategy for comparing two items.

6. Where Strategy is used:

  • Payment methods: card, UPI, wallet, cash on delivery
  • Sorting and filtering options in a product list
  • Different tax rules for different countries
  • Login methods: password, Google, OTP
  • Compression or export formats: ZIP vs GZIP, CSV vs PDF

Part 2: The Observer Pattern

1. The problem:

When a customer places an order, many things must happen: send a confirmation email, reserve the stock, record the sale for analytics, maybe notify the warehouse. The naive version calls them all directly:

function placeOrder(order) {
  saveOrder(order);
  sendEmail(order);
  reserveStock(order);
  trackRevenue(order);
  notifyWarehouse(order);
}

Now the order code depends on email, inventory, analytics and the warehouse. Every new reaction means editing placeOrder. And if you want to turn analytics off in tests, you have to change this function.

2. The idea:

The Observer pattern (also called publish/subscribe) splits this into two roles:

  • The subject (or publisher) keeps a list of listeners and announces events: “an order was placed”.
  • The observers (or subscribers) register their interest and react when the event happens.

The subject does not know what the observers do. It just tells everyone who signed up.

3. Building a tiny event emitter:

class EventEmitterLite {
  #listeners = new Map(); // event name -> Set of functions

  on(event, listener) {
    if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());
    this.#listeners.get(event).add(listener);
    return () => this.off(event, listener); // handy unsubscribe function
  }

  off(event, listener) {
    this.#listeners.get(event)?.delete(listener);
  }

  emit(event, data) {
    for (const listener of this.#listeners.get(event) ?? []) {
      listener(data);
    }
  }
}

That is the whole pattern: a map of event names to sets of functions, a way to add and remove them, and a loop that calls them.

4. Using it for orders:

class OrderService extends EventEmitterLite {
  placeOrder(order) {
    console.log(`Order ${order.id} saved`);
    this.emit("orderPlaced", order);
  }
}

const orders = new OrderService();

orders.on("orderPlaced", (o) => console.log(`Email: thanks ${o.customer}, order ${o.id} received`));
orders.on("orderPlaced", (o) => console.log(`Inventory: reserve ${o.items.length} item(s)`));
const stopAnalytics = orders.on("orderPlaced", (o) => console.log(`Analytics: revenue +${o.total}`));

orders.placeOrder({ id: "A101", customer: "Aisha", items: ["book", "pen"], total: 640 });
// Order A101 saved
// Email: thanks Aisha, order A101 received
// Inventory: reserve 2 item(s)
// Analytics: revenue +640

stopAnalytics();
orders.placeOrder({ id: "A102", customer: "Rahul", items: ["lamp"], total: 900 });
// Order A102 saved
// Email: thanks Rahul, order A102 received
// Inventory: reserve 1 item(s)

OrderService has no idea that email, inventory or analytics exist. Adding a warehouse notification is one more orders.on(...) line somewhere else in the app. Removing analytics was a single call to the function on returned.

5. Node.js already has it:

Node’s built-in EventEmitter is exactly this pattern, with extras such as once:

const { EventEmitter } = require("node:events");
const bus = new EventEmitter();

bus.on("signup", (u) => console.log(`Welcome email to ${u.email}`));
bus.once("signup", () => console.log("First signup ever!"));

bus.emit("signup", { email: "a@example.com" });
// Welcome email to a@example.com
// First signup ever!
bus.emit("signup", { email: "b@example.com" });
// Welcome email to b@example.com

console.log(bus.listenerCount("signup")); // 1

In the browser, button.addEventListener("click", ...) is the Observer pattern too. So are React state updates that re-render the components that use the state, RxJS observables, and webhooks between services.

6. Things to watch out for:

One failing listener can stop the rest. In our simple emitter, if a listener throws, the loop stops:

const safe = new EventEmitterLite();
safe.on("x", () => { throw new Error("boom"); });
safe.on("x", () => console.log("second listener"));

try { safe.emit("x"); } catch (e) { console.log("emit threw:", e.message); }
// emit threw: boom

“second listener” never ran. Node’s EventEmitter behaves the same way. If listeners are independent, wrap each call in try/catch inside emit, and log the error.

Memory leaks. A listener keeps the objects it uses alive. If a component subscribes and never unsubscribes, it stays in memory forever. Always remove listeners you no longer need (that is why our on returns an unsubscribe function, and why React effects return a cleanup function). Node even prints a warning when one event gets more than 10 listeners, because that is often a leak.

Hidden flow. With direct calls you can read placeOrder and see what happens. With events, the reactions live elsewhere, so name your events clearly and keep the list of listeners easy to find.

Order and timing. Listeners run in the order they were added, and synchronously. A slow listener slows down placeOrder. For heavy work (sending emails, resizing images), the listener should hand the job to a background queue instead.

Strategy and Observer Together:

The two patterns often appear side by side. Here is a small post publisher. Each social network is a strategy with its own length limit and formatting, and the results are announced as events:

const { EventEmitter } = require("node:events");

const networks = {
  x: { limit: 280, format: (text) => text },
  linkedin: { limit: 3000, format: (text) => `${text}\n\n#webdev` },
  bluesky: { limit: 300, format: (text) => text },
};

class Publisher extends EventEmitter {
  publish(text, networkNames) {
    for (const name of networkNames) {
      const strategy = networks[name];
      const body = strategy.format(text);
      if (body.length > strategy.limit) {
        this.emit("failed", { name, reason: `too long (${body.length}/${strategy.limit})` });
        continue;
      }
      this.emit("published", { name, length: body.length });
    }
  }
}

const publisher = new Publisher();
publisher.on("published", ({ name, length }) => console.log(`OK  ${name} (${length} chars)`));
publisher.on("failed", ({ name, reason }) => console.log(`ERR ${name}: ${reason}`));

publisher.publish("New lesson: the Strategy and Observer patterns in JavaScript!", ["x", "linkedin", "bluesky"]);
// OK  x (61 chars)
// OK  linkedin (70 chars)
// OK  bluesky (61 chars)

publisher.publish("a".repeat(290), ["x", "linkedin", "bluesky"]);
// ERR x: too long (290/280)
// OK  linkedin (299 chars)
// OK  bluesky (290 chars)

Adding a new network is one more entry in networks, and adding a new reaction (a dashboard, a retry queue, a notification) is one more listener. Real social media schedulers, such as Ralvana Social, which publishes one post to networks like X, LinkedIn, Bluesky and Threads, face exactly this problem: every network has its own rules, and the app must react to each success or failure.

Strategy vs Observer:

  • Strategy answers “how should this one task be done?” The context uses one strategy at a time, and it usually needs a result back (a price, a sorted list).
  • Observer answers “who needs to know that this happened?” The subject notifies many observers, and it usually does not care about their results.

When Not to Use Them:

Patterns are tools, not goals. If you have two shipping methods that will never change, a simple if is easier to read than four classes. If exactly one thing should happen after an order, call it directly. Reach for Strategy when the list of options keeps growing, and for Observer when several independent parts of the app must react to the same event.

Conclusion:

The Strategy pattern moves each variant of a behaviour into its own object or function, so you can add new variants without editing the code that uses them. The Observer pattern lets one object announce events while any number of listeners react, so features stay loosely coupled.

You use both every day: array.sort with a compare function is Strategy, and addEventListener and Node’s EventEmitter are Observer. Remember to unsubscribe listeners you no longer need, guard against errors in listeners, and keep it simple when a plain if is enough.

In the next Low Level Design lesson, we will look at Clean Architecture Explained, and see how these ideas shape a whole application.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume