What you'll learn: By the end of this lesson you will be able to say what a design pattern is and what it is not, name the three groups of classic patterns, recognise Composite, Factory, Decorator and Singleton in a front-end code base, predict what changes when decorators are stacked in a different order, explain why a singleton makes tests depend on each other, and decide when a plain function is a better answer than a pattern.
Carpenters have names for joints: mortise and tenon, dovetail, lap. The names do not build a table. They let two carpenters agree in one sentence on how two boards meet, what holds them, and what will fail first when the wood moves. A design pattern is that kind of name for a recurring shape in code: a short name for a problem that keeps coming back, the usual answer, and what the answer costs.
The running example is an order dashboard: a header, a filter bar, a table of orders and a side panel. The page layout comes from a small configuration that says which widgets to show, so teams can add a widget without touching the page. The lab's names and numbers are made up for the lesson.
The core idea
- A pattern is a blueprint, not code. Refactoring.guru describes patterns as typical solutions to commonly occurring problems in software design, and says a pattern is not a piece of code you copy but a general concept for solving a problem that you adapt to your program.
- The value is the vocabulary and the consequences. "This is a Decorator, so the order of the layers matters" is useful before you read a line of code. The class diagram is the least important part.
- Patterns are not free. The same site lists the criticisms: patterns can make up for missing language features (it says Strategy can often be replaced by a simple anonymous function), can be applied as a dogma, and can be used when simpler code would do.
Three illustrations run through the lesson: a minimal example (a small tree of text and buttons built from data), a realistic example (the order dashboard, with a wrapped data call), and a failure example (a shared singleton that leaks state between tests, and a layout that names a widget the page does not know).
This lesson builds on Component-Based Architecture, which cuts a page into a tree of components. The next lesson covers Observer, pub/sub and Mediator, and a later one Command, Strategy, Adapter and Facade. Here the focus is how a page is built and wrapped.
What a pattern is, and the three groups
Refactoring.guru describes a pattern in four parts: an intent (a brief summary of problem and solution), a motivation (why the problem exists and why the solution helps), a structure (the classes and how they relate) and a code example. It also compares an algorithm to a recipe, because an algorithm always defines a clear set of actions, and a pattern to a blueprint, because the code can differ from one program to the next.
Its catalogue sorts the classic patterns into three groups:
| Group | Concern | Members listed on that site |
|---|---|---|
| Creational | How objects are made | Factory Method, Abstract Factory, Builder, Prototype, Singleton |
| Structural | How objects are put together | Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy |
| Behavioral | How objects share work and talk | Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor |
The platform already contains some of them: MDN describes the DOM as a tree of nodes (Composite), EventTarget as the interface of objects that receive events and may have listeners (Observer), and Proxy as an object that wraps a target and intercepts operations through traps. React's useSyncExternalStore takes a subscribe function that returns a cleanup function, which is Observer with its unsubscribe built in.
Composite: a page is a tree
MDN says the DOM represents a document as a logical tree, and that every object in a document is a node of some kind, an element, a text node or an attribute node. Refactoring.guru's Composite lets you compose objects into tree structures and treat individual objects and compositions the same way: there is a component interface, leaves that do the work and containers that hold children, know them only through the interface and combine their results.
Figure 1. A composite tree: leaves and containers answer the same questions
How to read this: a caller that asks the root for count() never checks which boxes are containers. The container asks its children and adds up.
This is the minimal example. In the lab, Text and Button are leaves and Stack is a container; all three implement render, count and height. The demo builds the tree above and prints nodes=6 height=3.
The cost Refactoring.guru names is that a shared interface can be hard to define when the elements differ widely, and may need to be so general that it is harder to understand.
Factory: building the tree from data
A page whose widgets are listed in a configuration needs something that turns a name such as "button" into an object. Refactoring.guru's Factory Method addresses code that calls concrete classes directly and becomes tightly coupled to them, so that each new type adds more conditionals. The lab uses the lighter, common front-end form: a registry that maps a type name to a function that builds a node.
Figure 2. From configuration to a node tree through a registry
How to read this: adding a widget type is one registration. The page code that walks the tree does not change. A type with no builder fails by name.
In the lab, createDefaultRegistry() registers text, button and stack, and create calls the builder, which receives a function to build its children. Two behaviours are tested: an unknown type throws UnknownWidgetError naming the type, even when it is deep in the tree, and registries are independent, so registering in one does not change another.
Decorator: layers around a function
Refactoring.guru's Decorator places objects inside wrapper objects that hold the new behaviour. Wrappers implement the same interface as what they wrap, so clients treat both alike, a wrapper forwards the request and can work before or after it, and because they stack, the order in which they are applied decides the combined behaviour. The cons it lists: it is hard to remove one wrapper from the middle of the stack, and hard to write a decorator whose result does not depend on its position.
In front-end code the wrapped thing is usually a function, such as a data call. The lab has three decorators over a Handler that takes a string and returns a string: withLog writes a line per call that reaches it, withCache remembers successful results, and withRetry calls the inner handler up to a number of times.
Figure 3. Log inside retry: every attempt is logged
How to read this: the layer closest to the base sees every attempt, the layer farthest out sees one call. Neither is wrong. They answer different questions.
Expected output, captured from a real run (Node 26.13.1; section 2 of the demo, where the base fails twice for the log and retry pair and once for the cache and retry pair):
=== 2. Decorator: the same layers in two orders (log and retry: base fails twice; cache and retry: base fails once)
log outside retry: result=A base calls=3 log lines=1
log inside retry: result=A base calls=3 log lines=3
cache outside retry: base calls=2 cache hits=1 misses=1
retry outside cache: base calls=2 cache hits=1 misses=2
The result and the number of base calls are the same in both orders. The log and the cache counters are not, and a dashboard that says "one request" in one place and "three requests" in another is the usual result of not choosing the order on purpose.
Singleton: one instance, and its price
Refactoring.guru's Singleton ensures a class has one instance and gives a global access point to it. It lists the cons: it violates the single responsibility principle because it solves two problems at once, it can hide poor design when components know too much about each other, and it makes unit testing of client code harder.
In a front end the singleton is often not a class but a module-level variable: the first caller creates the object and everyone after gets the same one. The lab shows the cost with a cart. Two simulated test cases run against getSharedCart(): the first adds apples, and the second starts with apples already in it, until a reset hook that exists only for tests is called. With createCart(), a factory, the second case starts empty.
Expected output, captured from a real run (Node 26.13.1; section 3 of the demo):
=== 3. Singleton versus factory: what a second test case sees
singleton, test A adds apples; test B starts with: [apples]
singleton after the reset hook: []
factory, test A adds apples; test B starts with: []
One shared object carries state from one case to the next, and a factory lets the caller decide who shares what. This is also how Dependency Injection and Separation of Concerns puts it: create the object at the edge and pass it in.
Choosing, and when to skip a pattern
Figure 4. Do I need a pattern here?
How to read this: the pattern is the third answer, not the first. A named problem that a function solves needs no class.
| Choice | Gain | Cost |
|---|---|---|
| Composite | One way to walk any tree | A broad interface that every node must satisfy |
| Registry (Factory) | New types without editing the walker | A runtime failure when a type has no builder |
| Decorator | Behaviour added without changing the wrapped function | Order-dependent results, hard to remove a middle layer |
| Singleton | One shared object, easy to reach | Shared state between tests and between features |
Build it: a tree, a registry, three wrappers and two carts
Goal. Build a tree from data through a registry, stack decorators in two orders and read the difference, and see a singleton leak state that a factory does not.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no browser, no DOM and no timer.
cd examples/frontend
pnpm install
cd labs/ui-design-patterns
pnpm test # 15 tests
node src/demo.ts
Steps.
- Run the tests, then the demo.
- In section 1, count the nodes the root reports, and find the line where an unknown type fails.
- In section 2, compare the log lines of the two orders, then the cache misses.
- In section 3, find what the second test case sees with the singleton.
Expected output, captured from a real run (Node 26.13.1; section 1):
=== 1. Composite and factory: one tree built from data, one interface for every node
stack
text "Order 17"
stack
text "2 items"
button [Pay]
button [Cancel]
nodes=6 height=3
unknown type: unknown widget type "chart"
after registering "chart": has chart=true
What the lab does not show. No real DOM, no framework and no rendering. render() returns text lines. The registry, the decorators and the cart are small models of the patterns, not how any framework implements them.
Break it. In test/patterns.test.ts, find the test "log outside retry sees one call; log inside retry sees every attempt". Swap the two layer arguments in one of its two stack(...) calls and the expected counts (1 and 3) stop matching. Put them back.
In practice: the dashboard that went blank
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The order dashboard's layout is a JSON configuration served by the back end. Over a year, five teams add widgets. The code that turns the configuration into components is a long switch, repeated in the page, in a print view and in a test helper (illustrative). Adding a widget means editing three files, and one of them is usually forgotten.
Starting architecture
Figure 5. Starting point: a switch in three places
How to read this: three copies of one decision drift apart. The first one to miss a new type shows the symptom.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Keep the switch, add a lint rule | Forgotten cases are reported | A rule to maintain | The three copies still exist |
| One shared registry (Factory) | One place to add a type | A migration of three callers | An unknown type now fails at one place for everyone |
| Registry plus a per-widget fallback | One place, and a bad type shows a placeholder | A fallback component | A placeholder can hide a real bug if nobody reads the report |
The decision
| Field | Decision record |
|---|---|
| Context | Three copies of a type switch drift; each new widget touches three files. |
| Decision | One registry, created by a function (not a shared instance), used by the page, the print view and the tests. An unknown type renders a labelled placeholder and is reported. |
| Consequences, good | A widget is added in one place, and tests build their own registry. |
| Consequences, bad | The registry is a runtime lookup, so a missing type is found at run time, not at compile time. |
| Revisit when | The number of types grows enough that code splitting each builder matters. |
Rollout and verification
- Introduce the registry beside the switch and make the page read from it, with the switch as a fallback for one release.
- Add a test that every type the back end can send is registered (see Contract Testing for Front Ends).
- Remove the switch everywhere.
The 2 a.m. failure
A back-end release adds a heatmap widget before the front-end release reaches every user. Users with the older cached page now receive a layout containing a type their registry does not have. create throws UnknownWidgetError for the whole tree, and the dashboard is blank (illustrative). First three checks: (1) read the error: it names the type; (2) compare the front-end version the user runs with the one that knows heatmap (see Version Skew and Cache-Busting Deployments); (3) check whether any error boundary caught it (see Error Boundaries and Global Error Handling). Mitigation: hide the new widget in the layout the back end serves to older versions. Follow-up: build each widget under its own fallback so one unknown type costs one panel, and add the contract test from the rollout. Exercise 3 asks for this.
Architect's notes
- Name the pattern in the review, but say the problem first: "three switches drift, so one registry".
- Prefer a function to a class when the pattern has one method.
- Create, do not share: return a new registry or store from a function, and decide where it is shared. A module-level instance is a decision with a testing cost.
- Choose the decorator order on purpose and write it next to the stack, because the logs and the counters depend on it.
Common mistakes
- Applying a pattern because it is on a list, when simpler code would do.
- A shared module-level instance that carries state from one test, or one feature, to the next.
- A decorator stack whose order nobody chose, so the log says one thing and the counter another.
- A registry that fails the whole page on one unknown type.
- A composite interface so wide that leaves implement methods they never use.
Key takeaways
- A pattern is a named solution with a stated cost, a blueprint rather than code.
- The classic catalogue has creational, structural and behavioral groups; the DOM and
EventTargetalready contain Composite and Observer. - Composite treats a leaf and a container alike; a registry builds nodes from data; a decorator wraps a function and its order changes what each layer sees.
- A singleton shares state; a factory lets the caller decide who shares.
- Ask first whether plain code or a function solves the problem.
Practice exercises
Exercise 1 — Starter (45 min): Add a Tabs container whose render prints only its active child, without changing any caller.
Exercise 2 — Intermediate (2 hours): Add a withTimeout decorator that uses an injected clock. Decide where in the stack it belongs relative to retry, and write one test for each position.
Exercise 3 — Advanced (half day): Change create so that an unknown type produces a placeholder node and a reported error instead of throwing. Write the test that reproduces the blank dashboard first, then make it pass.
Related reading
In this course:
- Component-Based Architecture, the tree of components that Composite describes.
- Dependency Injection and Separation of Concerns, creating objects at the edge instead of sharing them.
- Ports and Adapters in the Front End, the structural patterns applied to a whole application.
- Presence and Pub/Sub, pub/sub over a network, which is the other side of the Observer idea.
Official documentation
- Refactoring.guru: What is a design pattern?, the definition and the three groups.
- Refactoring.guru: Composite, Decorator, Singleton and Factory Method.
- Refactoring.guru: Criticism of patterns.
- MDN: Using the Document Object Model, the DOM as a tree of nodes.
- MDN: Proxy and EventTarget.
- React: useSyncExternalStore, a subscription with a cleanup function.