Patterns your language already has

  • Lesson 30 of 32
  • 10 min
  • Beginner
  • 11 steps

Many patterns from the 1994 book already live inside the languages you use every day. You will spot them in `addEventListener`, in a plain function, in `for…of`, in `Proxy` and in Python's `@`, and learn when a class of your own is still worth it.

Pattern classes you write
—
Built into the language
—
UserCartaddButtonordersaddButtonBadgeupdateBadgesendEmailupdateBadgeAnalyticstrackupdateStocktrackObserverinterfaceObserverCheckoutpay()undo[]pay()noneremove anonetenOffremove bBlackFridaytenOfffor…ofSetSetyour codeProxyProxyuseruserfib(30)@lru_cache@lru_cachefib()fib()hand-written subscribe() and notify()your interfaceObserver written by handinterface Observer {update(count: number): void;}class Badge implements Observer {update(count: number) { show(count); }}▸cart.subscribe(new Badge());16 of 23, simplerPattern and what your language shipsObserveraddEventListener, on()Strategya functionCommanda stored functionIteratorfor…ofProxynew Proxy()Decorator@ in Pythonthe DOM ships ita functionObserver with the DOM+addButton.addEventListener(+"click", updateBadge);+addButton.addEventListener(▸"click", track, { once: true });emit(): synchronous1st2ndObserver with EventEmitterimport { EventEmitter } from "node:events";const orders = new EventEmitter();+orders.on("paid", sendEmail);+orders.on("paid", updateStock);▸orders.emit("paid", order);// sendEmail, then updateStocka functionreceives and callsStrategy as a function▸type Discount = (total: number) => number;const none: Discount = (t) => t;const tenOff: Discount = (t) => t * 0.9;function pay(total: number, d: Discount) {return d(total);}pay(100, tenOff); // 90pop() and runthe last onewaits its turnCommand as a function+const undo: Array<() => void> = [];function addItem(id: string) {cart.add(id);▸undo.push(() => cart.remove(id));}+undo.pop()?.(); // Ctrl+Z{ value, done }asks next()Iterator with for…ofconst tags = new Set(["js", "ts", "js"]);▸for (const tag of tags) {console.log(tag); // js, ts}const it = tags[Symbol.iterator]();it.next(); // { value: "js", done: false }set trapthe real objectProxy with new Proxy()const user = new Proxy({ age: 0 }, {▸set(target, key, value) {if (key === "age" && value < 0)throw new RangeError("age < 0");target[key] = value; return true;} });−user.age = -1; // RangeError2nd time: from the cacheonly the 1st timeDecorator with @ in Pythonfrom functools import lru_cache▸@lru_cache(maxsize=None)def fib(n):if n < 2:return nreturn fib(n - 1) + fib(n - 2)fib(30) # 832040state + 2 methodsState and two methods: a classclass BlackFriday {▸used = 0;apply(total: number) {this.used++;return total * 0.8;}▸left() { return 100 - this.used; }}built into the languagePatterns your language already hasObserveraddEventListener, on()Strategya functionCommanda stored functionIteratorfor…ofProxynew Proxy()Decorator@ in Pythonyour own classwith state and several methods
  • request
  • response
  • event
  • failed request

Step 1 of 11

Problem

You copy the diagram from the book

You want the cart counter and the analytics to know when someone adds a product. You open the Observer diagram and copy it as is: an Observer interface, a Badge class that implements it, an Analytics class, and in Cart a list of observers with subscribe() and a loop that calls update().

It works, but that is three new pieces and a subscription mechanism you have to test and maintain. In the browser that mechanism already exists, and you use it every time you listen for a click.

What changed

  • interface Observer
  • Badge and Analytics
  • Cart.subscribe()

Step 2 of 11

Concept

Your language already has several

The 1994 book describes the patterns with C++ and Smalltalk classes. In 1996, Peter Norvig showed in his talk on patterns in dynamic languages that 16 of the 23 become invisible or simpler when the language has functions as values and other features C++ lacked.

That is why «I don't use patterns» is rarely true: you use them through the language. The table is the map of this lesson; each row has its own lesson in the course if you want to see the class version.

What changed

  • pattern → language feature

Step 3 of 11

Solution

Observer: `addEventListener`

In the DOM, a button is an EventTarget: you register functions with addEventListener("click", fn) and it calls them when the event happens. You can register several functions for the same event, just like several observers.

It also ships what you would have written to unsubscribe: removeEventListener, the { once: true } option, which removes the listener after the first call, or a signal from an AbortController. Zero classes of your own.

What changed

  • interface Observer and its classes
  • addEventListener

Step 4 of 11

Technique

In Node: `EventEmitter`

On the server you get the same with EventEmitter, from the node:events module. You subscribe with on("paid", fn) and notify with emit("paid", order). So when an order is paid, sendEmail and updateStock find out without the payment code knowing them.

Two details worth knowing: emit calls the listeners synchronously and in the order they were registered, not in the background. And if one event gets more than 10 listeners, Node prints a warning by default, to help you catch leaks.

What changed

  • EventTarget → EventEmitter

Step 5 of 11

Solution

Strategy: a function

To change how a discount is computed you do not need an interface and one class per rule. In JavaScript and TypeScript functions are values: the contract is a function type, (total: number) => number, and each rule is a function that fits it.

pay(100, tenOff) returns 90 and pay(100, none), 100. The caller receives the rule and calls it without knowing which one it is. It is the same idea as the Strategy lesson, with less code.

What changed

  • interface Discount and its classes
  • type Discount = function

Step 6 of 11

Technique

Command: a stored function

Command turns an action into something you can store and run later. With functions as values, the action can be a function with no arguments that you keep in a list: every time you add a product, you push the function that removes it.

Ctrl+Z takes the last one with undo.pop() and runs it. The list is your history and each function remembers its id through its closure. If you also need redo or a name for each action, the Command lesson teaches the object version.

What changed

  • undo: Array<() => void>
  • pay() → undo[]

Step 7 of 11

Solution

Iterator: `for…of`

You never wrote a hasNext() to walk an array, and you do not need to: JavaScript ships the iteration protocol. An iterable has a [Symbol.iterator]() method that returns an object with next(), and each next() hands back { value, done }.

for…of calls next() for you until done is true. Array, String, Map and Set are already iterable; here the Set drops the repeated "js" and the loop prints js and ts. The Iterator lesson shows how to make your own collection iterable.

What changed

  • hand-written hasNext() and next()
  • for…of

Step 8 of 11

Solution

Proxy: the `Proxy` object

A Proxy stands in front of an object with the same face and decides what to do with each access. JavaScript ships it as new Proxy(object, handler): the handler has traps such as get or set that intercept reading or writing a property.

Here the set trap lets user.age = 30 through and rejects user.age = -1 with a RangeError before it touches the object. Whoever uses user does not know someone is in the middle. The set trap returns true to say the write succeeded.

What changed

  • new Proxy(object, { set })

Step 9 of 11

Solution

Decorator: Python's `@`

A Decorator wraps something to add behaviour without changing it. Python has syntax for it: writing @lru_cache(maxsize=None) above def fib is the same as fib = lru_cache(maxsize=None)(fib). The @ is only syntactic sugar.

functools.lru_cache returns a function that memoises results: the first call with an argument reaches fib, later ones come from the cache. Since the name fib now points to the wrapped version, the recursive calls go through the cache too, and fib(30) gives 832040 without repeating work.

What changed

  • @lru_cache

Step 10 of 11

Trade-off

When the class still wins

A function is enough while it is one method with no state. When the Black Friday rule starts counting how many times it was used and answering how many are left, it has state and two methods. Spreading that over loose variables and several functions hides it; a named class shows it and can be tested on its own.

The shortcut has a cost too: an anonymous function says less than a class called BlackFriday, and an emit does not show you who is listening. Use what the language ships for the simple case and move to the class version when the code really grows, not before.

What changed

  • tenOff → BlackFriday
  • state and left()

Step 11 of 11

Summary

Before copying the diagram, check your language

Observer lives in addEventListener and EventEmitter; Strategy and Command, in a function; Iterator, in for…of; Proxy, in Proxy; Decorator, in Python's @. You use them every day even if you do not call them by name.

Before writing the book's interface and classes, look for the piece your language already has. Move to a class of your own when that piece needs state and several methods.

You will learn

  • Notice when you are hand-copying a pattern your language already has.
  • Use `addEventListener` and `EventEmitter` as Observer.
  • Write Strategy and Command as functions.
  • See Iterator, Proxy and Decorator in `for…of`, `Proxy` and Python's `@`.
  • Know when a named class is still the better choice.