Design Patterns: Strategy, Observer, and Decorator
Here and in the next posts, I will talk about design patterns, it’s definition, the guiding design principles they embody, and their C# examples. But before you dive into design patterns, here is a refresher on four OO basics.
Design Pattern #1: Strategy Pattern
- Defines a family of algorigthms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
- Design Principles:
- Design Principle #1 : Separate code that change from code that stays the same
- Design Principle #2 : Program to an interface and not to an implementation
-
Design Principle #3 : Favor composition (HAS-A) over inheritance (IS-A)
- Note: To implement composition, a class will have an interface type reference to a concrete implementation that is usually initialized during the class constructor
- C# Examples:
- Basic calculation of two numbers (+,-) that can expand to any number of operators (/,*,etc.)
- Simple shipping cost calculation that can take in different shipping methods. This example also shows how to implement the strategy pattern using the delegate approach.
- Consultant search algorithm using different strategies. It also has delegate implementation.
Design Pattern #2: Observer Pattern
- Defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. A good example is a newspaper publisher and its subscribers.
- Design Principles:
- Design Principle #4 : Strive for loosely coupled designs between objects that interact
- C# Examples:
Design Pattern #3: Decorator Pattern
- Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality. It does this by using composition and delegation. Decorator classes have same types as the components they decorate, either through inheritance or interface implementation. They add behavior by adding new functionality before and/or after method calls to the component.
- Design Principles:
- Design Principle #5 : Classes should be open for extension but closed for modification
- C# Examples: