Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 57 ยท Practice and Interview Prep

Design Pattern Exercises with Solutions

Practice 15 design pattern exercises across creational, structural and behavioral patterns, each with a short runnable JavaScript solution and review hints.

Reading about patterns is not the same as using them. This lesson gives you 15 exercises, five each for creational, structural and behavioral patterns. Every exercise states a small problem, names the pattern that fits, and lists what a good solution must do. Then a runnable solution follows.

Use the lesson like this: read an exercise, close the solutions, and write your own version in the editor. Only then compare. Your names and structure will differ, and that is fine. What matters is that your design meets the requirements and that you can explain why the pattern fits. The solutions are intentionally short; they are stand-ins for production code, not frameworks.

How to use the exercises

Read Understand the requirements first.
Try Write your own solution before looking.
Compare Check each requirement against the answer.
Explain Say why the pattern fits.
1 / 2

Creational exercises

Exercise 1: Settings registry (Singleton). An app needs one shared settings object. It must be created once, readable everywhere and must not be replaced or mutated by accident. Provide get(key) and make a second import or creation attempt return the same instance. See Singleton.

Exercise 2: Notifier factory (Factory Method). Create notifiers for email, sms and push. Calling code asks for a type by name and uses send(to, text). An unknown type must fail with a clear message, and adding a new type must not change the calling code. See Factory Method.

Exercise 3: Themed widgets (Abstract Factory). A light theme and a dark theme each produce a matching Button and Panel. The app picks a theme once and never mixes light and dark widgets. See Abstract Factory.

Exercise 4: Request builder (Builder). Build an immutable HTTP request with a required URL, optional method, headers and a body. build() must reject a GET with a body and a missing URL. See Builder.

Exercise 5: Template clone (Prototype). A report template has a title and a list of sections. Create new reports by cloning a template. Changing a clone's sections must not change the template (a deep copy). See Prototype.

Solutions: creational

A few notes before the code. In solution 1, a frozen object created once in a module is the JavaScript way to get a singleton; no class machinery is needed. In solution 2, a registry (a Map) replaces an if chain, so a new notifier registers itself. In solution 5, structuredClone makes the deep copy.

JS Creational solutions (exercises 1 to 5)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reflect.set reports false instead of throwing, so the example behaves the same in strict and sloppy code. Assigning directly would throw a TypeError in a module. Either way the frozen object is protected.

Review hints. Did your singleton avoid global mutable state? Did your factory fail loudly on unknown input? Did the builder validate in build(), not in each setter? Did the clone share nothing with the template?

Structural exercises

Exercise 6: Temperature adapter (Adapter). A legacy sensor returns Fahrenheit through readF(). Your code expects an object with readCelsius(). Wrap the sensor without changing it. See Adapter.

Exercise 7: Text pipeline (Decorator). Start with a function that returns plain text. Add decorators that trim, uppercase and append an exclamation mark. They must stack in any order. See Decorator.

Exercise 8: Menu totals (Composite). A lunch menu contains items with prices and combo boxes that contain items or other combos. Ask any of them for its price() the same way. See Composite.

Exercise 9: Caching proxy (Proxy). A slow lookup function is called repeatedly with the same keys. Add a proxy with the same interface that caches results and exposes how many real calls were made. See Proxy.

Exercise 10: Checkout facade (Facade). Placing an order needs inventory, payment and shipping subsystems. Provide one placeOrder(item, card) method that coordinates them and reports success or the first failure. See Facade.

Solutions: structural

JS Structural solutions (exercises 6 to 10)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The facade returns the first failure and never calls later subsystems after it. A production version would also undo the reservation if payment fails, which is a good follow-up exercise using the Command pattern.

Review hints. Does the adapter leave the legacy class untouched? Could your decorators be applied in any order? Does your composite treat leaves and groups through one method? Does the proxy have exactly the same call shape as the real thing?

Behavioral exercises

Exercise 11: Shipping cost (Strategy). Compute shipping with three rules: standard (flat 5), express (10 plus 2 per kg) and free over a threshold. Choose the rule at run time and add a fourth without editing the calculator. See Strategy.

Exercise 12: Price alerts (Observer). A stock ticker publishes prices. Observers can subscribe and unsubscribe. An alert fires when the price crosses their threshold. After unsubscribing, an observer must not be called. See Observer.

Exercise 13: Counter with undo (Command). A counter supports add(n) and multiply(n) as commands. Undo must restore the exact previous value, even after several steps. See Command.

Exercise 14: Document workflow (State). A document is draft, review or published. submit, approve and reject are allowed only in some states. Illegal calls report an error instead of changing anything. See State.

Exercise 15: Support escalation (Chain of Responsibility). A ticket has a priority. A bot handles low, an agent handles medium, a manager handles high. Each handler either handles the ticket or passes it on; unhandled tickets are reported. See Chain of Responsibility.

Solutions: behavioral

JS Behavioral solutions (exercises 11 to 15)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 13 has a trap. If every command wrote its "before" value onto the shared counter, the second command would overwrite the first command's memory and only one step could be undone. Here each command instance keeps its own before, and the editor keeps a stack of commands, so any number of steps can be undone in order.

Review hints. Is the strategy table open for extension? Does unsubscribing really stop notifications? Does undo restore values after several steps? Are illegal state transitions rejected without side effects? Does the chain end with a clear "unhandled" outcome?

Stretch exercises

If you want more, change the solutions above:

  • Make the notifier factory return a decorated notifier that logs every send. Which two patterns work together?
  • Replace the workflow table with state objects. When does the table stop being enough?
  • Add a Memento to the counter so a snapshot can be saved and restored by name.
  • Replace the singleton settings object with a parameter passed to each function. What did you gain for testing?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In exercise 2 the notifier types live in a Map. What does this achieve compared with an if/else chain?

    Looking a type up in a registry keeps the factory closed to modification and open to new types.
  2. 2. Why did the Prototype exercise use a deep copy?

    A shallow copy duplicates only the top level. Nested arrays and objects would still be shared.
  3. 3. What is the main difference between the Adapter and the Facade exercises?

    Adapter converts one interface to another. Facade simplifies access to a group of components.
  4. 4. Why does the observer solution return a function from subscribe?

    A returned unsubscribe function is a simple, safe way to stop notifications.
  5. 5. What was wrong with storing a single 'before' value on the counter for undo?

    Multi-step undo needs a stack of earlier values, one entry per executed command.

Summary

  • Each pattern fits a specific pressure: one instance, creation by name, families, step-by-step construction, copying, translation, stacking behavior, trees, access control, simplification, swappable rules, notification, requests as objects, status-driven behavior and handler chains.
  • In JavaScript many patterns shrink to functions, Map registries, closures and frozen objects.
  • Compare your solution with the requirements, not with the shape of the sample code.
  • Watch for traps: shallow copies, one-step undo, validation spread over setters, and listeners that are never removed.
  • Combine patterns in the stretch exercises; real designs usually do.

Next lesson: Low-Level Design Exercises with Solutions.