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.
Write a factory function createAccount(owner) that keeps balance private and returns deposit, withdraw (refusing to go below 0 by throwing) and getBalance.
Add a once(event, fn) method to the Emitter class from the first example.
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
How do you get private state in JavaScript? Give three ways.
What is the difference between the observer pattern and pub/sub?
Why can a singleton be a problem, and what does JavaScript give you instead?
Explain the strategy pattern with an example from the standard library.
Preview
Console
Nothing logged yet.Expected console output
9 13
Unknown shape: blob
standard=60 express=150 pickup=0
true light