# Design Patterns: Module, Factory, Observer

> Learn the architectural blueprints of software design. Discover how to encapsulate data, manufacture objects, and broadcast events using classic patterns.

Subject: JavaScript | Lesson 57 of 63 | 8 min read
Interactive lesson: https://codewithanimation.in/javascript/design-patterns
Previous: [Memoization & Currying](https://codewithanimation.in/javascript/memoization-and-currying.md) | Next: [Immutability & Pure Functions](https://codewithanimation.in/javascript/immutability-and-pure-functions.md)

## Software Blueprints

A **Design Pattern** is a proven, standardized solution to a common software engineering problem. They are not specific libraries or frameworks, but conceptual templates for writing clean, maintainable code.

## The Big Three in JavaScript

1. **The Module Pattern**: Used to encapsulate 'private' variables and functions, exposing only a public API. Historically achieved using Closures (IIFEs), but now natively supported via ES Modules (`export`/`import`).

2. **The Factory Pattern**: A function that creates and returns new objects without using the `new` keyword or classes. Ideal when the object creation process is complex.

3. **The Observer Pattern (Pub/Sub)**: A 'Subject' maintains a list of 'Observers'. When the Subject's state changes, it automatically broadcasts a notification to all subscribed Observers.

## The Observer Pattern in Action

You use the Observer pattern every day without realizing it. Every time you write `button.addEventListener('click', fn)`, the button is the *Subject*, and your function is the *Observer*.

```javascript
class Subject {
  constructor() { this.observers = []; }
  subscribe(fn) { this.observers.push(fn); }
  publish(data) {
    this.observers.forEach(fn => fn(data));
  }
}
```

When `publish('hello')` is called, every function sitting in the `observers` array executes simultaneously.

## Common mistake: Over-Engineering

The biggest danger with Design Patterns is 'Patternitis'-trying to force a complex pattern into a simple problem just to look smart.

If you only need a single object, just write an object literal. Don't write a Singleton Factory Abstract Provider unless the architecture actually demands it.

## Tip: React and Observers

Modern state management libraries like Redux or Zustand are heavily built on the Observer pattern. Your React components *subscribe* to the global store, and when an action is dispatched (published), all subscribed components automatically re-render.

## Try it: The Observer Architecture

Study the architecture diagram below. It maps out the one-to-many relationship of the Observer pattern, where a single central Subject broadcasts data to multiple independent Subscribers.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/design-patterns

## Check yourself

### Question 1

Which Design Pattern is responsible for hiding private data and exposing only a public API?

- A. The Module Pattern
- B. The Observer Pattern
- C. The Factory Pattern

Correct answer: A

The Module pattern encapsulates logic, keeping variables safe from the global scope while explicitly exporting what is allowed to be used.

- Why not B: Incorrect. Observer is for event broadcasting.
- Why not C: Incorrect. Factory is for object creation.

### Question 2

If you call a function `createEnemy(type, level)` and it returns a customized object without using the `new` keyword, what pattern are you likely using?

- A. The Factory Pattern
- B. The Module Pattern
- C. The Observer Pattern

Correct answer: A

A Factory is simply a function that manufactures and returns objects. It abstracts away the complex setup logic so the caller doesn't have to worry about it.

- Why not B: Incorrect. Modules organize code, they don't dynamically stamp out new objects on demand.
- Why not C: Incorrect. Observer handles events, not object creation.

### Question 3

In the Observer pattern, what happens when the Subject calls `publish(data)`?

- A. It loops through its internal list of subscribers and executes all of them, passing the data along.
- B. It creates a new object.
- C. It caches the data for later.

Correct answer: A

The Subject is a broadcaster. It maintains an array of callback functions (subscribers) and simply loops through that array, executing each one when an event occurs.

- Why not B: Incorrect. That is the Factory pattern.
- Why not C: Incorrect. That is Memoization.

## Remember this

- Design Patterns are proven, conceptual templates for solving common architectural problems.
- The **Module Pattern** encapsulates private logic and exposes a public API.
- The **Factory Pattern** uses a function to manufacture and return objects, abstracting away complex creation logic.
- The **Observer Pattern** (Pub/Sub) allows a central Subject to maintain a list of dependents and notify them automatically of state changes.
- DOM Event Listeners and Redux stores are classic implementations of the Observer pattern.
