Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.2 — Design Patterns in JavaScript
JavaScript · Example 2 of 3

Factory, strategy and singleton

Changing the config through b changed it for a too: there is only one instance.

Design patterns are named, proven shapes for common code problems; in JavaScript the everyday ones are the module (private state), observer and pub/sub (notify listeners), factory (build the right object), singleton (one shared instance) and strategy (swap the algorithm).

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a factory function createAccount(owner) that keeps balance private and returns deposit, withdraw (refusing to go below 0 by throwing) and getBalance.

02

Add a once(event, fn) method to the Emitter class from the first example.

03

Replace this switch with a strategy object: function discount(type, price) { switch (type) { case "student": return price * 0.5; case "senior": return price * 0.7; default: return price; } }.

Explain it without notes

01

How do you get private state in JavaScript? Give three ways.

02

What is the difference between the observer pattern and pub/sub?

03

Why can a singleton be a problem, and what does JavaScript give you instead?

04

Explain the strategy pattern with an example from the standard library.

Factory, strategy and singleton

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

9 13
Unknown shape: blob
standard=60 express=150 pickup=0
true light