Sunday, September 7, 2008

Strategy Pattern

The strategy pattern (also known as the policy pattern) allows algorithms to be selected at runtime.

The strategy pattern defines a family of algorithms, encapsulate each one, and makes them interchangeable. It lets the strategy (algorithm) to vary independently from the clients that use it.

The pattern uses composition instead of inheritance thus giving the flexibility to change the algorithm dynamically by a simple setStrategy() call. Each algorithm is given its own class.


//StrategyExample test application
public class StrategyExample {

public static void main(String[] args) {
Context context;

context = new Context(new ConcreteStrategyA());
context.execute();

context.setStrategy(new ConcreteStrategyB());
context.execute();
}
}
interface IStrategy {
void execute();
}


class ConcreteStrategyA implements IStrategy {
public void execute() {
System.out.println( "Called ConcreteStrategyA.execute()" );
}
}

class ConcreteStrategyB implements IStrategy {
public void execute() {
System.out.println( "Called ConcreteStrategyB.execute()" );
}
}


class Context {
IStrategy strategy;

// Constructor
public Context(IStrategy strategy) {
this.strategy = strategy;
}

public void setStrategy(IStrategy is){
this.strategy = is;
}

public void execute() {
this.strategy.execute();
}
}


(Example based on the example from wikipedia)
In this example the Context class execute method calls the execute method of the IStrategy class to do some task. The IStrategy interface is implemented by ConcreteStrategyA and ConcreteStrategyB, and the Context's class's method setStrategy can be called anytime to change the strategy from A to B, so that the execute function can switch the algorithm is uses whenever we change the strategy object.

No comments:

Related Posts with Thumbnails