Files
Design-Patterns/docs/principles.md
2026-08-13 22:47:17 -04:00

1.9 KiB

← Design patterns index

Principles these examples keep demonstrating

These seven patterns all apply the same handful of ideas from Dive Into Design Patterns' design-principles chapter:

  • Encapsulate what varies. Each pattern isolates the one thing that changes: the platform (Bridge), the added behavior (Decorator), the subsystem wiring (Facade), the collaboration rules (Mediator), the saved state (Memento), the reaction to a change (Observer), or the state-specific behavior (State). Everything else stays untouched.

  • Program to an interface, not an implementation. IMessageSender, IShape, IObserver, IMemento, IOriginator, and State all exist so that a context or client depends on a contract instead of a concrete type. Subject.Notify() calls observer.Update() through IObserver alone, which is exactly why Data never needs to know that PieChart or BarGraph exists.

  • Favor composition over inheritance. Bridge, Decorator, Mediator, and State all answer "my class hierarchy is exploding" the same way: give the object a reference to another object instead of subclassing again. Shvets: "with composition you can easily substitute the linked 'helper' object with another, changing the behavior of the container at runtime."

  • Single Responsibility. "A class should have just one reason to change." Visible in ShapeDecorator subclasses (one behavior each), the State subclasses (one state each), and Facade (all engine sequencing in one place).

  • Open/Closed. "Classes should be open for extension but closed for modification." The concrete test: adding a new IObserver, a new ShapeDecorator, a new IMessageSender, or a new State requires zero edits to existing classes. Adding a state to BadCarState requires editing four separate switch statements — that's the principle failing, made visible.