This is previous handout modified a slightly, now with the answer

 

The Strategy Design Pattern: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.  Here is a general form

 

 

 

New to this previously handed out document: 

1. Added a setStrategyMethod

2. Add this specific UML class diagram of a boring strategy

 

 

Write the output of the following code

 

public class Structure {

  public static void main(String[] args) {

    // Three contexts following different strategies

    Context c = new Context(new ConcreteStrategyA());

    c.ContextInterface();

   

    Strategy b = new ConcreteStrategyB();

 

    Context d = new Context(b);

    d.ContextInterface();

   

    Context e = new Context(new ConcreteStrategyC());

    e.ContextInterface();

    e.setStategy(b);

    e.ContextInterface();

  }

}

 

 

Text Box: Answer
A's strategy
B's strategy
Third strategy 
B's strategy

 

 

 

 

 

 

 



 

 

// ------------------------------------------------------------

interface Strategy {

  abstract public void AlgorithmInterface();

}

 

// ------------------------------------------------------------

class Context {

  Strategy strategy; // an interface implemented by 3 concrete classes

 

  public Context(Strategy strategy) {

    this.strategy = strategy;

  }

 

  public void ContextInterface() {

    strategy.AlgorithmInterface();

  }

 

  public void setStategy(Strategy strategy) {

    this.strategy = strategy;

  }

}

 

// ------------------------------------------------------------

class ConcreteStrategyA implements Strategy {

  public void AlgorithmInterface() {

    System.out.println("A's strategy");

  }

}

 

// ------------------------------------------------------------

class ConcreteStrategyB implements Strategy {

  public void AlgorithmInterface() {

    System.out.println("B's strategy");

  }

}

 

// ------------------------------------------------------------

class ConcreteStrategyC implements Strategy {

  public void AlgorithmInterface() {

    System.out.println("Third strategy ");

  }

}