1.9 KiB
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, andStateall exist so that a context or client depends on a contract instead of a concrete type.Subject.Notify()callsobserver.Update()throughIObserveralone, which is exactly whyDatanever needs to know thatPieChartorBarGraphexists. -
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
ShapeDecoratorsubclasses (one behavior each), theStatesubclasses (one state each), andFacade(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 newShapeDecorator, a newIMessageSender, or a newStaterequires zero edits to existing classes. Adding a state toBadCarStaterequires editing four separateswitchstatements — that's the principle failing, made visible.