This repository contains small, browser-based examples of common software design patterns implemented in JavaScript.
The examples use older ES5-style JavaScript—constructor functions, prototypes, global variables, and var. The syntax may be old, but the design ideas are still useful in modern JavaScript applications.
No installation or build step is required.
- Choose an example directory.
- Open its
index.htmlfile in a browser. - Open the browser developer tools and select the Console tab.
- Read
main.jsand predict its output. - Refresh the page to check your prediction.
- Modify the example and observe how its behavior changes.
For the Strategy painter example, interact with the canvas instead of looking for console output.
- Simple Factory
- Strategy
- Observer
- Iterator
- Decorator
- Factory Method
- Abstract Factory
- Singleton/Namespace
Design patterns are commonly grouped into three categories:
- Creational patterns control how objects are created.
- Structural patterns organize relationships between objects.
- Behavioral patterns organize communication and responsibilities.
This repository implements examples from all three categories.
Category: Creational
Location: factory/simple-factory
A Simple Factory puts object-creation decisions in one place. The calling code asks for a type of object without directly invoking its constructor.
The factory creates either an Admin or a Customer:
function Admin() {
console.log("Admin created!");
}
function Customer() {
console.log("Customer created!");
}
var UserFactory = {};
UserFactory.createUser = function (type) {
if (type === "admin") {
return new Admin();
} else if (type === "customer") {
return new Customer();
}
};
var user = UserFactory.createUser("admin");Console output:
Admin created!
Customer created!
Use a factory when object construction depends on input, configuration, environment, or runtime state. Examples include creating users, parsers, database adapters, or UI controls.
Add a Guest constructor and support UserFactory.createUser("guest"). Also throw an error when the requested type is unknown.
Category: Creational
Location: factory/factory-method
The Factory Method pattern defines a creation operation that specialized objects can override. Client code uses the same method while different implementations decide which concrete product to return.
Every pizza store has a createPizza method, but each regional store creates a different style:
var PizzaStore = {
createPizza: function (type) {
// Create a generic pizza.
}
};
var ChicagoPizzaStore = fromPrototype(PizzaStore, {
createPizza: function (type) {
if (type === "veggie") {
return fromPrototype(Pizza, {
description: "Veggie, Deep-dish Chicago Pizza"
});
}
}
});Console output:
Veggie, Deep-dish Chicago Pizza
- A Simple Factory usually has one function containing all creation decisions.
- A Factory Method lets specialized implementations override the creation operation.
Use it when a base workflow should remain consistent but subclasses or specialized objects need to choose the object being created.
Create a NewYorkPizzaStore that supports cheese and veggie pizzas with thin crust.
Category: Creational
Location: factory/abstract-factory
An Abstract Factory creates a related family of objects without exposing their concrete implementations.
The example creates compatible groups of pizza ingredients:
var Ingredients = {
createDough: function () {
return "generic dough";
},
createSauce: function () {
return "generic sauce";
},
createCrust: function () {
return "generic crust";
}
};
Ingredients.createCaliforniaStyle = function () {
return fromPrototype(Ingredients, {
createDough: function () {
return "light, fluffy dough";
},
createSauce: function () {
return "tangy red sauce";
},
createCrust: function () {
return "thin and crispy";
}
});
};Console output:
thin and crispy
- A Factory Method generally creates one product through an overridable method.
- An Abstract Factory creates a family of related products that should work together.
Use it for themes, operating-system-specific controls, database provider families, or related application services that must remain compatible.
Add a New York ingredient family with thin dough, tomato sauce, and a crispy crust.
Category: Creational
Location: singleton/namespace
A Singleton normally ensures that only one instance of something exists and provides a shared access point to it.
The repository example mainly demonstrates the related namespace pattern. It creates one global container to avoid placing many separate names in the global scope:
var NAMESPACE = {};
NAMESPACE.Widget = function (foo, bar) {
this.foo = foo;
this.bar = bar;
};
NAMESPACE.Widget.prototype.doSomethingAwesome = function () {
console.log("Something awesome!");
};
var myWidget = new NAMESPACE.Widget("hello", "world");The original example produces no console output because its method body is only a placeholder.
var settings = (function () {
var instance;
function createSettings() {
return { theme: "dark" };
}
return {
getInstance: function () {
if (!instance) {
instance = createSettings();
}
return instance;
}
};
}());
var first = settings.getInstance();
var second = settings.getInstance();
console.log(first === second); // trueSingleton-like objects may be useful for shared configuration, logging, or application-wide services. Use them carefully because hidden global state makes testing and dependency management harder.
Implement NAMESPACE.Settings.getInstance() and prove that repeated calls return the same object.
Category: Structural
Locations: decorator/sale, decorator/sale-closures, and decorator/validator
A Decorator adds behavior to an object without permanently changing the original object or creating a subclass for every possible combination.
The sale begins at $50. One decorator adds federal tax and another formats the result as Canadian currency:
var sale = new Sale(50);
sale = sale.decorate("fedtax");
sale = sale.decorate("cdn");
console.log(sale.getPrice());Console output:
CDN$52.50
Decorators can be stacked, so the output of one decorator becomes the input to the next.
The closure variation wraps a function:
function usd(fn, context) {
var price = fn.call(context);
return "$" + price;
}
sale.getPrice = decorate(usd, sale.getPrice, sale);Wrapping the function three times produces:
$$$50
$$$100
Validation rules are selected dynamically:
var validator = new Validator();
validator.decorate("hasName", { length: 5 });
validator.decorate("hasAge", { minimum: 21 });
validator.decorate("hasZipCode");
validator.validate({});Console output:
["no name!", "no age!", "no zip!"]
Use decorators for optional formatting, logging, caching, authorization, validation, middleware, or pricing rules.
Add a discount decorator that reduces the price by 10%, then test whether applying tax before the discount gives the same result as applying the discount before tax.
Category: Behavioral
Locations: iterator/arrays and iterator/objects
An Iterator provides a consistent interface for traversing a collection without exposing how that collection is stored.
The repository iterators expose four operations:
next()returns the next value.hasNext()checks whether another value exists.current()returns the current value.rewind()moves back to the beginning.
The array iterator advances three positions at a time:
while (iterator.hasNext()) {
console.log(iterator.next());
}If this loop is added to the repository example, it prints:
1
4
7
10
The object iterator uses Object.keys() to traverse object values:
while (iterator.hasNext()) {
console.log(iterator.next());
}It prints:
foo
bar
baz
The original iterator files do not print anything because they define the iterators without calling their methods.
JavaScript now has built-in iteration tools such as for...of, generators, and Symbol.iterator. The repository demonstrates the underlying idea manually.
Change the array iterator so that its step size is provided as an argument rather than always being 3.
Category: Behavioral
Location: observer/publisher
The Observer pattern allows one object—the publisher—to notify multiple interested objects—the subscribers—when an event occurs.
The publisher exposes these operations:
on(type, fn, context)subscribes a function.fire(type, publication)publishes an event.remove(type, fn, context)unsubscribes a function.
The repository defines the publisher but does not register or fire any events. Add this code to try it:
function showMessage(message) {
console.log("Received: " + message);
}
publisher.on("news", showMessage);
publisher.fire("news", "JavaScript patterns are useful");
publisher.remove("news", showMessage);
publisher.fire("news", "This will not be printed");Expected output:
Received: JavaScript patterns are useful
Browser events use the same general idea:
button.addEventListener("click", handleClick);The button is the publisher, handleClick is the subscriber, and click is the event type.
Use it for UI events, notifications, application event buses, state subscriptions, and communication between loosely coupled components.
Subscribe two functions to the same event, publish once, remove one subscriber, and publish again.
Category: Behavioral
Location: strategy/painter
The Strategy pattern stores interchangeable algorithms behind a common interface. The application selects the behavior it needs at runtime.
The painter contains three brush strategies. Each has the same draw method but implements it differently:
var brushes = {
outline: {
draw: function (event, context) {
context.strokeRect(event.pageX, event.pageY, 10, 10);
}
},
square: {
draw: function (event, context) {
context.fillRect(event.pageX, event.pageY, 10, 10);
}
},
circle: {
draw: function (event, context) {
context.arc(event.pageX, event.pageY, 10, 0, Math.PI * 2);
context.fill();
}
}
};The drawing code does not need to know which shape is selected:
brush.draw(event, context);Clicking a button replaces the active strategy:
brush = brushes[brushType];Use Strategy when an application needs interchangeable sorting, payment, authentication, validation, compression, routing, or pricing algorithms.
Add a largeSquare or line brush. It should provide the same draw(event, context) interface as the existing brushes.
| Example | Result |
|---|---|
| Simple Factory | Admin created!, then Customer created! |
| Factory Method | Veggie, Deep-dish Chicago Pizza |
| Abstract Factory | thin and crispy |
| Decorator: Sale | CDN$52.50 |
| Decorator: Sale Closures | $$$50, then $$$100 |
| Decorator: Validator | ['no name!', 'no age!', 'no zip!'] |
| Iterator: Arrays | No output until iterator methods are called |
| Iterator: Objects | No output until iterator methods are called |
| Observer | No output until subscribers and events are added |
| Singleton/Namespace | No output |
| Strategy: Painter | Interactive canvas; no console output |
Use this loop for every example:
Predict -> Run -> Modify -> Break -> Repair -> Rebuild from memory
After understanding an example, recreate it in another domain. For instance:
- Factory: create notification providers such as email, SMS, and push.
- Strategy: select credit card, UPI, or wallet payment behavior.
- Observer: notify UI components when application state changes.
- Decorator: add logging, caching, and authorization around a service.
- Iterator: traverse a custom tree or paginated result set.
The main goal is not to memorize the code. Learn to recognize the problem each pattern solves, the parts allowed to vary, and whether the pattern makes the program clearer than a simpler function or object would.
The original project plan mentioned several additional Gang of Four patterns, including Builder, Prototype, Adapter, Composite, Facade, Proxy, Command, Mediator, State, Template Method, and Visitor. They do not currently have example directories in this repository.
- Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides
- JavaScript Patterns by Stoyan Stefanov
- The original article series: http://robdodson.me/blog/2012/08/03/javascript-design-patterns/