38 lines
1.9 KiB
Markdown
38 lines
1.9 KiB
Markdown
[← Design patterns index](README.md)
|
|
|
|
# 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.
|