Design Patterns
Two families of reusable design knowledge. The twelve classic Gang of Four patterns describe how objects get made, fit together and talk. The five SOLID principles describe what makes those objects easy to change. Each entry gives the rule, a working example in eight languages, and a link to its deep dive.
Start from the problem you have. Every entry below is a brief: what the idea is, the call you would write, and where it already appears in real code. Open the deep dive for the diagram, the annotated working code, the trade-offs and the pitfalls, all switchable across eight languages.
12 Design Patterns
Twelve classic patterns, grouped by intent. Creational patterns control how objects are made, structural patterns control how they compose, and behavioral patterns control how they communicate. Each brief shows the call you would write in your own language.
Creational
How objects get made. Hide the new, control how many exist, or copy what you have.
Singleton
Singleton guarantees one shared instance and a single way to reach it. It solves the problem of three modules each opening their own connection pool and exhausting the database. The instance is created on first use and reused forever after. The deep dive shows why a module-level global is often the better answer in modern code.
A real example you can run
class ConnectionPool {
static created = 0;
private static current: ConnectionPool | null = null;
readonly id: string;
private constructor() {
ConnectionPool.created += 1;
this.id = "pool-" + ConnectionPool.created;
console.log("pool created: " + this.id);
}
static get instance(): ConnectionPool {
if (ConnectionPool.current === null) {
ConnectionPool.current = new ConnectionPool();
}
return ConnectionPool.current;
}
}
const orders = ConnectionPool.instance;
const users = ConnectionPool.instance;
const reports = ConnectionPool.instance;
console.log("orders -> " + orders.id);
console.log("users -> " + users.id);
console.log("reports -> " + reports.id);
console.log("pools created: " + ConnectionPool.created);
// prints:
// pool created: pool-1
// orders -> pool-1
// users -> pool-1
// reports -> pool-1
// pools created: 1Factory Method
Factory Method moves object creation behind a function. Instead of scattering new SmsNotifier and new EmailNotifier across the codebase, callers ask for a kind and receive something that already fits the expected interface. Adding a variant touches the factory, not every call site. The deep dive builds one that selects a notifier by name.
A real example you can run
interface Notifier {
send(to: string, message: string): void;
}
class EmailNotifier implements Notifier {
send(to: string, message: string): void {
console.log("email -> " + to + ": " + message);
}
}
class SmsNotifier implements Notifier {
send(to: string, message: string): void {
console.log("sms -> " + to + ": " + message);
}
}
class PushNotifier implements Notifier {
send(to: string, message: string): void {
console.log("push -> " + to + ": " + message);
}
}
function createNotifier(kind: string): Notifier {
if (kind === "email") return new EmailNotifier();
if (kind === "sms") return new SmsNotifier();
return new PushNotifier();
}
createNotifier("email").send("ada@example.com", "order shipped");
createNotifier("sms").send("+15550100", "order shipped");
createNotifier("push").send("device-9", "order shipped");
// prints:
// email -> ada@example.com: order shipped
// sms -> +15550100: order shipped
// push -> device-9: order shippedBuilder
Builder replaces a long positional constructor with named steps. A query with optional filters reads far better as chained calls than as six boolean arguments where order matters and nothing is named. Each step records intent, and the final build validates the whole thing. The deep dive assembles a query object and shows what the equivalent argument list looks like.
A real example you can run
class QueryBuilder {
private table = "";
private conditions: string[] = [];
private params: string[] = [];
private order = "";
private cap = 0;
from(table: string): QueryBuilder {
this.table = table;
return this;
}
where(column: string, op: string, value: string): QueryBuilder {
this.conditions.push(column + " " + op + " ?");
this.params.push(column + "=" + value);
return this;
}
orderBy(column: string): QueryBuilder {
this.order = column;
return this;
}
limit(n: number): QueryBuilder {
this.cap = n;
return this;
}
build(): string {
if (this.table === "") throw new Error("from() is required");
let sql = "SELECT * FROM " + this.table;
if (this.conditions.length) sql += " WHERE " + this.conditions.join(" AND ");
if (this.order) sql += " ORDER BY " + this.order;
if (this.cap) sql += " LIMIT " + this.cap;
return sql;
}
boundParams(): string {
return this.params.join(", ");
}
}
const query = new QueryBuilder()
.from("orders")
.where("status", "=", "paid")
.where("total", ">", "100")
.orderBy("created_at")
.limit(20);
console.log(query.build());
console.log("params: " + query.boundParams());
// prints:
// SELECT * FROM orders WHERE status = ? AND total > ? ORDER BY created_at LIMIT 20
// params: status=paid, total=100Prototype
Prototype creates new objects by copying an existing one. When construction is expensive or the setup is elaborate, cloning a configured template beats repeating the work. The subtle part is depth: shared nested objects must be copied too, or editing the clone silently changes the original. The deep dive clones a shape with a nested style and proves the two are independent.
A real example you can run
interface Theme {
color: string;
}
class CampaignTemplate {
constructor(
public subject: string,
public body: string,
public theme: Theme,
) {}
clone(): CampaignTemplate {
return new CampaignTemplate(this.subject, this.body, structuredClone(this.theme));
}
}
const original = new CampaignTemplate("Spring sale", "Save 20% this week", {
color: "#1a73e8",
});
const clone = original.clone();
clone.subject = "Spring sale (VIP)";
clone.theme.color = "#d93025";
console.log("original: subject=" + original.subject + ", color=" + original.theme.color);
console.log("clone: subject=" + clone.subject + ", color=" + clone.theme.color);
console.log("original after clone edit: subject=" + original.subject + ", color=" + original.theme.color);
// prints:
// original: subject=Spring sale, color=#1a73e8
// clone: subject=Spring sale (VIP), color=#d93025
// original after clone edit: subject=Spring sale, color=#1a73e8Structural
How objects fit together. Wrap, translate, simplify or guard other objects.
Adapter
Adapter lets two pieces of code cooperate when their interfaces disagree. A third-party SDK has its own method names, units and error shapes, but your checkout already expects one stable interface. A thin wrapper translates between them, so the seam lives in one file instead of leaking everywhere. The deep dive adapts a payment SDK to the interface the rest of the app already speaks.
A real example you can run
interface Receipt {
id: string;
approved: boolean;
}
interface PaymentGateway {
pay(amountInCents: number, currency: string): Receipt;
}
class StripeSdk {
chargeCard(majorUnits: number, currencyCode: string, cents: number): Receipt {
console.log("sdk: charged " + majorUnits.toFixed(2) + " " + currencyCode);
return { id: "rcpt_1001", approved: cents > 0 };
}
}
class StripeAdapter implements PaymentGateway {
constructor(private readonly sdk: StripeSdk) {}
pay(amountInCents: number, currency: string): Receipt {
return this.sdk.chargeCard(amountInCents / 100, currency, amountInCents % 100);
}
}
function checkout(gateway: PaymentGateway): void {
const cents = 1250;
console.log("checkout: charging " + (cents / 100).toFixed(2) + " USD");
const receipt = gateway.pay(cents, "USD");
console.log("receipt: " + receipt.id + " approved=" + receipt.approved);
}
checkout(new StripeAdapter(new StripeSdk()));
// prints:
// checkout: charging 12.50 USD
// sdk: charged 12.50 USD
// receipt: rcpt_1001 approved=trueDecorator
Decorator adds behaviour by wrapping an object that shares its interface. Logging, caching and retries become small wrappers you stack in any order, instead of flags multiplying inside one class. Because every wrapper looks like the thing it wraps, callers never know how deep the stack is. The deep dive builds three wrappers around one flaky client and shows the cache short-circuiting a retry.
A real example you can run
interface HttpClient {
get(path: string): string;
}
class RawClient implements HttpClient {
private attempts = new Map<string, number>();
get(path: string): string {
const seen = (this.attempts.get(path) ?? 0) + 1;
this.attempts.set(path, seen);
if (seen === 1) throw new Error("network down");
return "rates-v1";
}
}
class WithRetry implements HttpClient {
constructor(private inner: HttpClient) {}
get(path: string): string {
try {
return this.inner.get(path);
} catch {
console.log("[retry] attempt 1 failed, retrying");
const body = this.inner.get(path);
console.log("[retry] attempt 2 ok");
return body;
}
}
}
class WithCache implements HttpClient {
private cache = new Map<string, string>();
constructor(private inner: HttpClient) {}
get(path: string): string {
const hit = this.cache.get(path);
if (hit !== undefined) return hit + " (cached)";
const body = this.inner.get(path);
this.cache.set(path, body);
return body;
}
}
class WithLogging implements HttpClient {
constructor(private inner: HttpClient) {}
get(path: string): string {
console.log("[log] GET " + path);
const body = this.inner.get(path);
console.log("[log] body: " + body);
return body;
}
}
const client = new WithLogging(new WithCache(new WithRetry(new RawClient())));
client.get("/rates");
client.get("/rates");
client.get("/quotes");
// prints:
// [log] GET /rates
// [retry] attempt 1 failed, retrying
// [retry] attempt 2 ok
// [log] body: rates-v1
// [log] GET /rates
// [log] body: rates-v1 (cached)
// [retry] attempt 1 failed, retrying
// [retry] attempt 2 ok
// [log] GET /quotes
// [retry] attempt 1 failed, retrying
// [retry] attempt 2 ok
// [log] body: rates-v1Facade
Facade puts one simple entry point in front of several collaborating parts. Placing an order means reserving stock, charging a card and scheduling delivery in the right order, and every caller should not have to know that sequence. The facade owns the order of operations and the error handling. The deep dive collapses a four-step checkout into a single call.
A real example you can run
// prints:
// order o-1: reserve 1 unit, charge 42.00, ship tomorrow
// order o-1 placed
// order o-2: reserve failed, out of stock
// order o-2 rejected, reservation released
class Inventory {
private stock = 2;
reserve(orderId: string, units: number): boolean {
if (this.stock < units) return false;
this.stock -= units;
return true;
}
}
class Payments { charge(orderId: string, amount: number): void {} }
class Shipping { schedule(orderId: string): void {} }
class CheckoutFacade {
private inventory: Inventory; private payments: Payments; private shipping: Shipping;
constructor(inventory: Inventory, payments: Payments, shipping: Shipping) { this.inventory = inventory; this.payments = payments; this.shipping = shipping; }
placeOrder(orderId: string, units: number, amount: number): boolean {
if (!this.inventory.reserve(orderId, units)) {
console.log("order " + orderId + ": reserve failed, out of stock");
console.log("order " + orderId + " rejected, reservation released");
return false;
}
console.log("order " + orderId + ": reserve " + units + " unit, charge " + amount.toFixed(2) + ", ship tomorrow");
this.payments.charge(orderId, amount);
this.shipping.schedule(orderId);
console.log("order " + orderId + " placed");
return true;
}
}
const facade = new CheckoutFacade(new Inventory(), new Payments(), new Shipping());
facade.placeOrder("o-1", 1, 42.0);
facade.placeOrder("o-2", 5, 42.0);Proxy
Proxy is a stand-in that controls access to another object while looking identical to it. It can defer expensive work until first use, check permissions before forwarding, or cache a result without the caller knowing. The difference from Decorator is intent: a proxy manages access, a decorator adds behaviour. The deep dive builds a lazy proxy that only constructs the heavy object on the first real call.
A real example you can run
interface DocumentService {
read(name: string): string;
}
class RealDocumentService implements DocumentService {
calls = 0;
read(name: string): string {
this.calls += 1;
return "Q3 revenue plan";
}
}
class PermissionProxy implements DocumentService {
constructor(private real: RealDocumentService, private role: string) {}
read(name: string): string {
if (this.role !== "editor") return "denied";
return this.real.read(name);
}
}
const real = new RealDocumentService();
const guest = new PermissionProxy(real, "guest");
const editor = new PermissionProxy(real, "editor");
console.log("guest read secret.txt: " + guest.read("secret.txt"));
console.log("editor read secret.txt: " + editor.read("secret.txt"));
console.log("real service calls: " + real.calls);
// prints:
// guest read secret.txt: denied
// editor read secret.txt: Q3 revenue plan
// real service calls: 1Behavioral
How objects talk. Who gets notified, who decides, who can undo.
Observer
Observer lets interested parties subscribe to changes instead of being called by name. The subject keeps a list of listeners and notifies them all when its state moves, so new consumers are added without touching the subject. The hard part is cleanup: a listener that never unsubscribes is a memory leak. The deep dive wires a store to a UI and a logger, then removes one subscriber.
A real example you can run
type Subscriber = (price: number) => void;
class PriceFeed {
private subscribers: Subscriber[] = [];
subscribe(subscriber: Subscriber): void {
this.subscribers.push(subscriber);
}
unsubscribe(subscriber: Subscriber): void {
this.subscribers = this.subscribers.filter((s) => s !== subscriber);
}
publish(price: number): void {
for (const subscriber of this.subscribers) subscriber(price);
}
count(): number { return this.subscribers.length; }
}
const feed = new PriceFeed();
const chart: Subscriber = (price) => console.log("chart: " + price);
const alert: Subscriber = (price) => {
if (price > 120) console.log("alert: " + price + " above 120");
};
feed.subscribe(chart);
feed.subscribe(alert);
for (const price of [118, 121, 117]) feed.publish(price);
feed.unsubscribe(chart);
feed.publish(130);
console.log("subscribers left: " + feed.count());
// prints:
// chart: 118
// chart: 121
// alert: 121 above 120
// chart: 117
// alert: 130 above 120
// subscribers left: 1Strategy
Strategy puts interchangeable algorithms behind one interface and picks one at runtime. Login by password, by one-time code or by a social provider becomes three implementations instead of one branch-heavy function. Adding a method means adding a class, not editing the dispatcher. The deep dive swaps authentication strategies and shows the call site staying identical.
A real example you can run
interface ShippingStrategy {
quote(weightKg: number): number;
}
class Standard implements ShippingStrategy {
quote(weightKg: number): number { return 5.0; }
}
class Express implements ShippingStrategy {
quote(weightKg: number): number { return 4.5 * weightKg; }
}
class FreeOver100 implements ShippingStrategy {
quote(weightKg: number): number { return 0.0; }
}
class ShippingCalculator {
strategy: ShippingStrategy;
constructor(strategy: ShippingStrategy) { this.strategy = strategy; }
setStrategy(strategy: ShippingStrategy): void { this.strategy = strategy; }
total(weightKg: number): string { return this.strategy.quote(weightKg).toFixed(2); }
}
const parcel = 2.5;
const calc = new ShippingCalculator(new Standard());
console.log("standard: " + calc.total(parcel));
calc.setStrategy(new Express());
console.log("express: " + calc.total(parcel));
calc.setStrategy(new FreeOver100());
console.log("free-over-100: " + calc.total(parcel));
// prints:
// standard: 5.00
// express: 11.25
// free-over-100: 0.00Command
Command turns an action into an object. Once an action is a value, it can be queued, logged, retried, grouped and reversed, which is how editors get undo and redraw. Each command knows how to apply itself and how to take itself back. The deep dive builds insert and delete commands over a history stack and undoes them in order.
A real example you can run
interface Command { apply(): void; revert(): void; }
class EditorBuffer { text = ""; }
class InsertCommand implements Command {
constructor(private readonly buffer: EditorBuffer, private readonly text: string) {}
apply(): void { this.buffer.text += this.text; }
revert(): void { this.buffer.text = this.buffer.text.slice(0, -this.text.length); }
}
class DeleteCommand implements Command {
private cut = "";
constructor(private readonly buffer: EditorBuffer, private readonly count: number) {}
apply(): void { this.cut = this.buffer.text.slice(-this.count); this.buffer.text = this.buffer.text.slice(0, -this.count); }
revert(): void { this.buffer.text += this.cut; }
}
class History {
private readonly done: Command[] = [];
run(command: Command): void { command.apply(); this.done.push(command); }
undo(): void { this.done.pop()?.revert(); }
}
const buffer = new EditorBuffer();
const history = new History();
history.run(new InsertCommand(buffer, "Hello"));
console.log("after insert: " + buffer.text);
history.run(new InsertCommand(buffer, " World"));
console.log("after insert: " + buffer.text);
history.run(new DeleteCommand(buffer, 6));
console.log("after delete: " + buffer.text);
history.undo();
console.log("undo: " + buffer.text);
history.undo();
console.log("undo: " + buffer.text);
// prints:
// after insert: Hello
// after insert: Hello World
// after delete: Hello
// undo: Hello World
// undo: HelloChain of Responsibility
Chain of Responsibility passes a request along a line of handlers. Each handler can act, forward, or stop the request, so auth, rate limiting and logging stay separate and reorderable. The caller sends once and does not know which handler answered. The deep dive builds a middleware chain where a rejected request never reaches the handler behind it.
A real example you can run
interface Handler {
handle(req: { token: string; count: number }): string;
setNext(next: Handler): void;
}
class BaseHandler implements Handler {
protected next: Handler | null = null;
setNext(next: Handler): void {
this.next = next;
}
handle(req: { token: string; count: number }): string {
return this.next ? this.next.handle(req) : "no handler";
}
}
class AuthHandler extends BaseHandler {
handle(req: { token: string; count: number }): string {
if (req.token === "") return "auth rejected, missing token";
return super.handle(req);
}
}
class RateLimitHandler extends BaseHandler {
handle(req: { token: string; count: number }): string {
if (req.count > 10) return "rate limit rejected, " + req.count + " over 10";
return super.handle(req);
}
}
class LogHandler extends BaseHandler {
handle(req: { token: string; count: number }): string {
const result = super.handle(req);
return "log ok, " + result;
}
}
class Terminal extends BaseHandler {
handle(): string {
return "handled with 200";
}
}
const log = new LogHandler();
log.setNext(new Terminal());
const rate = new RateLimitHandler();
rate.setNext(log);
const auth = new AuthHandler();
auth.setNext(rate);
const requests = [
{ token: "", count: 3 },
{ token: "t1", count: 12 },
{ token: "t1", count: 3 },
];
requests.forEach((req, i) => {
console.log("req " + (i + 1) + ": " + auth.handle(req));
});
// prints:
// req 1: auth rejected, missing token
// req 2: rate limit rejected, 12 over 10
// req 3: log ok, handled with 2005 SOLID Principles
SOLID is five principles for object-oriented design that keep a codebase easy to change. Each one below gives the rule in a sentence, the symptom that points to a violation, and a link to the deep dive with the broken version, the fix and a diagram.
SOLID Principles
SOLID is five habits that keep a codebase easy to change as it grows. Each letter targets one kind of pain: a module that does too much, a switch you edit for every new feature, a subclass that breaks its parent, an interface that forces unused work, and business logic welded to a database. The overview shows all five side by side so you can match a symptom to a principle.
Single Responsibility
Every module should have exactly one reason to change. When a sign-up function also sends email, hashes passwords and writes to the database, a change to the email copy can break the password path. Splitting each concern into its own unit means a change touches one file for one reason. The deep dive starts from a function doing all four jobs and separates them step by step.
A real example you can run
class UserValidator {
validate(email: string): boolean {
console.log("validating " + email);
return email.includes("@");
}
}
class PasswordHasher {
hash(password: string): string {
console.log("hashing password");
return "h1";
}
}
class UserStore {
private nextId = 1;
save(email: string, hash: string): number {
const id = this.nextId++;
console.log("storing user " + id + " " + email + " hash=" + hash);
return id;
}
}
class WelcomeMailer {
send(email: string): void {
console.log("sending welcome to " + email);
}
}
class SignupService {
constructor(
private validator: UserValidator,
private hasher: PasswordHasher,
private store: UserStore,
private mailer: WelcomeMailer,
) {}
register(email: string, password: string): number {
if (!this.validator.validate(email)) throw new Error("invalid email");
const hash = this.hasher.hash(password);
const id = this.store.save(email, hash);
this.mailer.send(email);
return id;
}
}
const service = new SignupService(
new UserValidator(),
new PasswordHasher(),
new UserStore(),
new WelcomeMailer(),
);
try {
console.log("signup ok: " + service.register("ada@example.com", "pw"));
} catch (err) {
console.log("signup failed: " + (err as Error).message);
}
try {
console.log("signup ok: " + service.register("not-an-email", "pw"));
} catch (err) {
console.log("signup failed: " + (err as Error).message);
}
// prints:
// validating ada@example.com
// hashing password
// storing user 1 ada@example.com hash=h1
// sending welcome to ada@example.com
// signup ok: 1
// validating not-an-email
// signup failed: invalid emailOpen/Closed
Code should welcome new behaviour without editing what already works. The usual smell is a growing switch statement that you reopen for every new case, which risks breaking the cases you did not touch. Instead, define a small interface and add a new implementation each time. The deep dive turns a discount switch into a list of discount rules, then adds a new promotion with zero edits to checkout.
A real example you can run
interface DiscountRule {
apply(cents: number): number;
}
class PercentOff implements DiscountRule {
constructor(private percent: number) {}
apply(cents: number): number {
return Math.round(cents * (100 - this.percent) / 100);
}
}
class GoldMember implements DiscountRule {
apply(cents: number): number {
return Math.max(0, cents - 500);
}
}
class BlackFriday implements DiscountRule {
apply(cents: number): number {
return Math.round(cents * 75 / 100);
}
}
class Checkout {
constructor(private rules: DiscountRule[]) {}
total(cents: number): number {
let result = cents;
for (const rule of this.rules) {
result = rule.apply(result);
}
return result;
}
}
const cart = 8000;
const cases: [string, DiscountRule[]][] = [
["percent-off", [new PercentOff(10)]],
["gold-member", [new GoldMember()]],
["black-friday", [new BlackFriday()]],
["all rules", [new PercentOff(10), new GoldMember(), new BlackFriday()]],
];
for (const [name, rules] of cases) {
console.log(name + ": " + new Checkout(rules).total(cart));
}
// prints:
// percent-off: 7200
// gold-member: 7500
// black-friday: 6000
// all rules: 5025Liskov Substitution
If a function accepts a base type, it must keep working when given any subtype. A subtype that throws where the parent succeeded, silently ignores a parameter or returns something weaker has broken the promise. This is why a read-only store should not pretend to be a writable one. The deep dive shows a subclass that throws on save and the contract split that fixes it.
A real example you can run
interface Readable {
read(key: string): string;
}
interface Writable extends Readable {
save(key: string, value: string): void;
}
class MemoryStore implements Writable {
private data = new Map<string, string>();
read(key: string): string {
return this.data.get(key) ?? "";
}
save(key: string, value: string): void {
this.data.set(key, value);
}
}
class ReadOnlyStore implements Readable {
constructor(private source: Writable) {}
read(key: string): string {
return this.source.read(key);
}
}
function saveMarker(store: Writable, label: string): string {
store.save("marker", label);
return store.read("marker");
}
const memory = new MemoryStore();
const readOnly = new ReadOnlyStore(memory);
console.log("write: " + saveMarker(memory, "v1"));
console.log("read via readonly: " + readOnly.read("marker"));
const writable: Writable[] = [memory];
console.log("writable stores: " + writable.length);
console.log("readonly is not writable: yes");
// prints:
// write: v1
// read via readonly: v1
// writable stores: 1
// readonly is not writable: yesInterface Segregation
No caller should depend on methods it never calls. One wide interface forces every implementer and every test fake to stub unrelated methods, and a change to one method ripples through all of them. Several small, focused interfaces keep each dependency honest. The deep dive splits a wide repository interface so a support bot only needs the lookup it actually uses.
A real example you can run
interface OrderLookup {
find(id: string): string;
}
interface OrderAdmin extends OrderLookup {
cancel(id: string): void;
deleteAll(): void;
}
class OrderRepository implements OrderAdmin {
private orders = new Map<string, string>([
["o-1", "shipped"],
["o-2", "pending"],
]);
find(id: string): string {
return this.orders.get(id) ?? "unknown";
}
cancel(id: string): void {
this.orders.set(id, "cancelled");
}
deleteAll(): void {
this.orders.clear();
}
}
class SupportBot {
constructor(private lookup: OrderLookup) {}
answer(id: string): string {
return "order " + id + ": " + this.lookup.find(id);
}
}
const repo = new OrderRepository();
const bot = new SupportBot(repo);
console.log(bot.answer("o-1"));
console.log(bot.answer("o-2"));
console.log("bot depends on " + 1 + " method");
console.log("admin keeps cancel and deleteAll: yes");
// prints:
// order o-1: shipped
// order o-2: pending
// bot depends on 1 method
// admin keeps cancel and deleteAll: yesDependency Inversion
Business rules should not depend on infrastructure details. When an order service constructs its own payment client, you cannot run a single test without hitting a real provider. Invert it by declaring the interface you need and accepting it from outside. The deep dive moves the choice of concrete class into one composition root and makes the service testable in a line.
A real example you can run
interface PaymentGateway {
charge(orderId: string, cents: number): string;
}
interface OrderStore {
save(orderId: string, status: string): void;
}
class StripeGateway implements PaymentGateway {
charge(orderId: string, cents: number): string {
return "paid " + cents + " for " + orderId;
}
}
class InMemoryOrders implements OrderStore {
private rows: string[] = [];
save(orderId: string, status: string): void {
this.rows.push(orderId + "=" + status);
}
dump(): string {
return this.rows.join(",");
}
}
class OrderService {
constructor(
private gateway: PaymentGateway,
private orders: OrderStore,
) {}
checkout(orderId: string, cents: number): string {
const receipt = this.gateway.charge(orderId, cents);
this.orders.save(orderId, "paid");
return receipt;
}
}
class FakeGateway implements PaymentGateway {
charge(orderId: string, cents: number): string {
return "fake charged " + cents;
}
}
const gateway = new StripeGateway();
const orders = new InMemoryOrders();
const service = new OrderService(gateway, orders);
console.log(service.checkout("o-1", 4200));
console.log("stored: " + orders.dump());
const testing = new OrderService(new FakeGateway(), new InMemoryOrders());
console.log(testing.checkout("o-9", 100));
// prints:
// paid 4200 for o-1
// stored: o-1=paid
// fake charged 100