Text & documents
Numbers & maths
Data & formats
Security
Development & DevOps
Artificial Intelligence
Finance
Health & Wellness
Productivity
Games & Entertainment
Multimedia & design
Business
How to use
See it run

Each pattern is a small program that actually runs in your browser. Press an action and the tool records every call between objects: from that it draws the sequence diagram (who calls whom, with what, and what comes back) and the object graph (who knows whom). The code you see is exactly the code that runs: step through it and the method behind each message is highlighted.

Sources

Gamma, Helm, Johnson and Vlissides, Design Patterns (1994): Builder p. 97, Factory Method p. 107, Singleton p. 127, Adapter p. 139, Composite p. 163, Decorator p. 175, Facade p. 185, Proxy p. 207, Chain of Responsibility p. 223, Command p. 233, Iterator p. 257, Mediator p. 273, Observer p. 293, State p. 305, Strategy p. 315 and Template Method p. 325. The examples and texts are our own. When to use it and when not: in /practices.

Design patternsStrategy, observer, command… actually running
Design patternsStrategy, observer, command… actually running

Each way of pricing shipping lives in its own interchangeable object: Checkout does not know which one it is using, only that it has a cost().

Switch the shipping and compute the total: in the trace, Checkout calls cost() on a different object, without a single if.

Shipping
StandardShipping

The code that runs

class StandardShipping {
cost(order) {
return order.weight <= 2 ? 4.99 : 4.99 + (order.weight - 2) * 1.5;
}
}
class ExpressShipping {
cost(order) {
return 9.99 + order.weight * 2;
}
}
class StorePickup {
cost(order) {
return 0;
}
}
class Order {
constructor(weight) {
this.weight = weight;
}
}
class Checkout {
constructor(shipping) {
this.shipping = shipping;
}
setShipping(shipping) {
this.shipping = shipping;
}
total(order, subtotal) {
return subtotal + this.shipping.cost(order);
}
}
function setup() {
const standard = new StandardShipping();
return {
order: new Order(3),
standard,
express: new ExpressShipping(),
pickup: new StorePickup(),
checkout: new Checkout(standard),
};
}
const actions = {
total: (w) => w.checkout.total(w.order, 30),
useStandard: (w) => w.checkout.setShipping(w.standard),
useExpress: (w) => w.checkout.setShipping(w.express),
usePickup: (w) => w.checkout.setShipping(w.pickup),
};

Sequence diagram · at setup

Step 5 of 5 you → Checkout: «new» Checkout(StandardShipping)
youStandardShippingOrderExpressShippingStorePickupCheckout1. «new» StandardShipping()2. «new» Order(3)3. «new» ExpressShipping()4. «new» StorePickup()5. «new» Checkout(StandardShipping)

Who knows whom

shippingStandardShippingOrderExpressShippingStorePickupCheckout