Nov 10, 2018

Strategy pattern

Head First Design Patterns

No 1 Design Principle in software development

The 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.






  1. Define the interface of an interchangeable family of algorithms
  2. Bury algorithm implementation details in derived classes
  3. Derived classes could be implemented using the Template Method pattern
  4. Clients of the algorithm couple themselves strictly to the interface

Design Patterns: Elements of Reusable Object-Oriented Software


Example 1:
interface sendStrategy() {
 public void send();
}

class sendByCopy implements sendStrategy() {
 public void send() {
  //copy to the send folder.
 }
}

class sendBySMTP implements sendStrategy() {
 public void send () {
 // send by connecting to SMTP
 }
}
Example 2:
// 1. Define the interface of the algorithm
interface Strategy { public void solve(); }        

// 2. implementation
abstract class TemplateMethod1 implements Strategy { 
// 3. Template Method
   public void solve() {
      // ... call start(), stop(), etc.
   }
   protected abstract void    start();
   protected abstract void    stop();
}

class Impl1 extends TemplateMethod1 {
   private int state = 1;
   protected void start() {
     System.out.print( "start  " );
   }
   protected void stop() {
     System.out.println( "stop" );
   }
}

// 2. another implementation
abstract class TemplateMethod2 implements Strategy { // 3. Template Method
   public void solve() {                          
      // ...
   }
}

class Impl2 extends TemplateMethod2 {
   // ...
}

// 4. Clients stick to the interface
public class StrategyDemo {
   public static void client( Strategy s ) {
     s.solve();
   }
}