Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 156 ยท Classes and Objects in Depth

JavaScript Design Patterns

Learn five practical JavaScript design patterns - module, observer, factory, singleton and strategy - with runnable examples and advice on when to use each.

A design pattern is a named, proven shape for solving a problem that keeps coming back. Nobody invented these patterns for JavaScript specifically; developers noticed the same solutions appearing in many programs and gave them names, so that "let's use an observer here" can replace a long explanation.

Patterns are not recipes to copy blindly. They are vocabulary. Used well, they make code easier to change and to talk about. Used everywhere, they bury simple code under ceremony. This lesson covers five patterns that show up constantly in real JavaScript: module, observer, factory, singleton and strategy. Each one builds on ideas from earlier lessons: closures, classes, composition and OOP principles.

The module pattern: private state, public API

The problem: you want some variables to stay hidden, and only a small set of functions to be visible to the outside. Before ES modules existed, developers solved this with a function that runs immediately and returns an object. The returned functions are closures over the hidden variables.

JS A counter module with private state

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

No output.

The assignment counter.count = 99 does not reach the private count; it just adds an unrelated property to the returned object. That is the whole point: the only way to change the real state is through the methods you chose to expose.

Today, a file that uses import and export is already a module: top-level variables are private to the file unless exported. The immediately-invoked version is still worth knowing, because you will see it in older code and because the same closure trick is how factories and many libraries keep their internals hidden.

The observer pattern: notify without knowing who listens

The problem: one part of the program changes, and several other parts need to react, but you do not want the first part to know about the others. In the observer pattern, a subject keeps a list of subscribers and calls each one when something happens. You already use this idea every time you call addEventListener.

flowchart LR
  S["Subject<br/>(emit)"] --> A["Subscriber A"]
  S --> B["Subscriber B"]
  S --> C["Subscriber C"]
  A -.->|"subscribe / unsubscribe"| S

The subject only knows a list of functions; it never needs to know what they do.

JS A tiny event emitter

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

No output.

Notice that Cart never mentions the badge or the banner. You can add a third subscriber without touching it. The price is indirection: when a bug appears, you cannot tell from add() alone what will run. Always return an unsubscribe function (or provide off), otherwise subscribers that are no longer needed stay in memory. Browsers also ship a built-in version: any EventTarget can dispatchEvent and addEventListener, which is often enough without writing your own emitter. See events for that API.

The factory pattern: create objects without new everywhere

A factory is a function that builds and returns objects. Callers say what they want; the factory decides how to build it. That is useful when creation involves choices, validation or setup that you do not want repeated at every call site.

JS A factory that picks the right shape

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

No output.

The caller never imports a Circle or Rect class; it only knows createShape. That makes it easy to add a new shape later, or to load the specs from JSON. Factories also give you something classes cannot: because they are plain functions, they can return objects with truly private state through closures, or return a cached object instead of a new one.

The same idea appears in the standard library: Array.from(), Object.create() and Intl.NumberFormat() (which works with or without new) are all factory-like.

The singleton pattern: exactly one instance

A singleton guarantees that only one instance of something exists and gives everyone the same one: an application configuration, a logger, a connection pool. In JavaScript the simplest singleton is no pattern at all. A module is evaluated once, so whatever it exports is shared by everyone who imports it.

JS Two ways to get one instance

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

No output.

Be careful with this pattern. A singleton is global state in disguise: any code can change it, tests leak into each other because the instance survives between them, and it hides dependencies. When something does not truly have to be unique, prefer creating it once at the top of your program and passing it in to the code that needs it. Reach for a real singleton only for things that are unique by nature, like a connection to one device.

The strategy pattern: swap an algorithm

The problem: you have several ways of doing one job (sorting, pricing, validating, formatting), and the right one depends on context. Instead of a growing if / else if chain, put each variant in its own function and pick one at runtime. In languages without first-class functions this needs a class per strategy. In JavaScript a strategy is just a function, stored in an object or passed as a parameter.

JS Pricing strategies chosen by name

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

No output.

Adding a new discount means adding one function; checkout never changes. This is the "open for extension, closed for modification" idea from OOP principles, and it is also what you are doing whenever you pass a comparison function to sort() or a callback to map().

Choosing a pattern

Patterns solve specific pains. Start from the pain, not from the pattern:

Pain Pattern
Internals leak or are easy to break Module (closures or ES modules)
One change must trigger many reactions Observer
Creation logic is repeated or complex Factory
Something must exist exactly once Singleton (or just a module)
One job with swappable algorithms Strategy

If your code is already clear, you probably do not need a pattern. Wait until duplication or tangling actually hurts, then pick the smallest tool that fixes it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the module pattern, how do the returned methods keep access to the private variables?

    The inner functions are closures, so they keep the outer function's variables alive even after it has returned, while nothing else can reach them.
  2. 2. What is the main benefit of the observer pattern?

    The subject only keeps a list of callbacks. New listeners can be added without changing the subject.
  3. 3. Why should an observer API return an unsubscribe function?

    Without a way to remove a handler, the subject holds a reference to it forever, which keeps the handler and everything it captures alive.
  4. 4. What is the simplest way to create a singleton in modern JavaScript?

    Every file that imports the module gets the same exported object, so no special class is needed.
  5. 5. In the strategy pattern in JavaScript, what usually plays the role of a strategy?

    Functions are first-class values, so each variant can be a plain function selected at runtime.

Summary

  • A design pattern is a named solution to a recurring problem; use it as vocabulary, not as a rule.
  • Module: closures (or ES modules) keep state private and expose a small public API.
  • Observer: a subject calls a list of subscribers; return an unsubscribe function to avoid leaks.
  • Factory: a function builds objects and hides the creation details from the caller.
  • Singleton: one shared instance; in JavaScript an exported module object does the job, but passing dependencies in is usually healthier.
  • Strategy: swap algorithms by storing functions in an object or passing them as arguments.

Next: Errors and try...catch - what happens when things go wrong, and how to handle it.