Strategy Pattern
Use the Strategy pattern when:
– you have many related classes differ only in their behavior.– you need different variants of an algorithm/functionality. variants can be
– you want to avoid exposing complex, algorithm-specific data structures to clients. An algorithm uses data that you want to hide it from client.
– you have a class that defines many behaviors, and these have multiple conditional statements in its operations
implemented as a class hierarchy.
public interface FlyBehavior{
public fly();
}
public class CantFly implements FlyBehavior{
public void fly(){
System.out.println("I can't fly");
}
}
public abstract class Duck {
public FlyBehavior flybehavior;
public void setFlyBehavior(FlyBehavior FB){
flybehavior = FB;
}
public void performfly(){
flybehavior.fly();
}
abstract display();
}
public class DecoyDuck extends Duck {
public DecoyDuck(){
setFlyBehavior(new CantFly);
}
public void display(){
System.out.println("I am a DecoyDuck");
}
}