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

 

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

 

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s