Strategy Pattern

 

The Strategy Pattern defines a family of algorithms, encapsulates them, and makes them interchangeable. Strategy lets the algorithms vary independently from the clients that use it.

It allows the selection of one of several algorirhms dynamically. Algorithms may be related via inheritance or implement the same interface.




Design principles (link):

  • (OK) Open Closed Principle - introduce new strategies without changing the context.
  • (OK) Liskov Substitution Principle - each algorithm in the Strategy pattern has the same functionality and can be swapped at runtime.
  • (OK) Interface Segregation Principle - all the concrete strategies should implement and use all functionalities of the Strategy interface.
  • (OK) Dependency Inversion Principle - context and concrete strategies depend on Strategy abstraction

Relations with Other Patterns

  • In the State pattern, a set of behaviours are encapsulated in state objects, and at any time the context delegates to one of these states. The current state changes to reflect the internal state of the context, so its behaviour changes overtime. The client knows very little about the state objects. In Strategy pattern, a family of algorithms are encapsulated in order to make them interchangeable. The client usually specifies the strategy object that the context is composed with.
  • Decorator lets you add new behaviour to an object, while Strategy lets you change the internal algorithm.
  • Strategy delegates work to the current subclass in the context, while Adapter always delegates work to the same class which it wraps.
  • Template Method is based on inheritance: it lets you alter parts of an algorithm by extending those parts in subclasses. Strategy is based on composition: you can alter parts of the object’s behavior by supplying it with different strategies that correspond to that behavior. Template Method works at the class level, so it’s static. Strategy works on the object level, letting you switch behaviors at runtime.

Comments

Popular Posts