Wednesday, June 4, 2014

Strategy Pattern

Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Allows for reuse of code through inheritance and composition
 
Use this pattern if you have to develop an application, that may change over time (it will change) or when features that are not known yet, should be added. The strategy pattern uses a number of design principles. I will try to explain each principle with an example.

Design Principle 1: Identify aspects of an application that vary and separate them form what stays the same. Encapsulate: Later you will be able to alter or extend the parts that vary without affecting other parts. Result: Fewer unintended consequences from code changes and more flexibility in a system. E.g.: use separate classes to delegate behavior - instanced by the class using those behaviors. This way it is also easy to change behavior on run time (getter, setter).

 class Dog(){  
     // (FightBehavior is an interface - multiple Behavior  
     // patterns may be implemented) same goes for PlayBehavior  
     FightBehavior fBehavior;  
     PlayBehavior pBehavior;  
     void fight();  
     void play();  
 }  

Design Principle 2: Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype.
e.g.: not Dog d = new Dog();
      d.bark();
      use Dog d = new Animal();
      d.makeNoise();

Design Principle 3: Favor composition (has-a relationships) over inheritance.
  • has-a:  each dog has a fight behavior to which it delegates fighting (behavior is being composed with the right behavior object
  • is-a: inheriting behavior from other classes
Strategy uml
 Remember: More time is spent on code after development is complete (maintaining and changing software).

No comments:

Post a Comment