Sunday, 23 April 2017

Strategy Pattern


Context has to be able to apply different Algorithms (strategies, actions, behaviours) in the runtime but is coupled with their implementations. It contains all possible concrete implementations of an Algorithm family and has to change if:
  • implementation of some Algorithm has to change
  • a new Algorithm has to be added or some existing has to be removed
This breaks Single Responsibility Principle (Context has to change for more than one reason) and Open-Closed Principle (Context has to be modified if list of Algorithms gets extended).


Remove Algorithm implementations out of the Context and separate them in their own classes which implement new interface IStrategy with method DoAlgorithm(). Introduce lookup table (Dictionary) which keeps all IStrategy implementations. When Context receives key from the input, it looks up the Dictionary and calls IStrategy implementation which matches the given key.


Strategy pattern
Applying Strategy Pattern Instead of Using Switch Statements
Post a Comment