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.Duck 问题(head frist oop)
有的能飞,有的能叫,经典问题.
//Duck.java public abstract class Duck { FlyBehavior flyBehavior; QuackBehavior quackBehavior; public Duck() { } public abstract void display(); public void performFly() { flyBehavior.fly(); } public void performQuack() { quackBehavior.quack(); } public void swim() { System.out.println(“All ducks float, even decoys!”); } }
public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } public void display() { System.out.println(“I’m a real Mallard duck”); } }
//Type and compile the FlyBehavior interface (FlyBehavior.java) and //the two behavior implementation classes (FlyWithWings.java and //FlyNoWay.java).
接口作为一个行为,因为有的能飞有的不能飞,所以不能够在父类里写fly(). 用一个interface作为一个行为汇总,interface下还有其他的行为. public interface FlyBehavior { public void fly(); }
public class FlyWithWings implements FlyBehavior { public void fly() { System.out.println(“I’m flying!!”); } }
public class FlyNoWay implements FlyBehavior { public void fly() { System.out.println(“I can’t fly”); } }
public interface QuackBehavior { public void quack(); }
public class Quack implements QuackBehavior { public void quack() { System.out.println(“Quack”); } }
public class MuteQuack implements QuackBehavior { public void quack() { System.out.println(“<< Silence >>”); } }
public class Squeak implements QuackBehavior {
public void quack() {
System.out.println(“Squeak”);
}
}
Setting behavior dynamically
//Add two new methods to the Duck class: public void setFlyBehavior(FlyBehavior fb) { fl yBehavior = fb; } public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; }
//Make a new Duck type (ModelDuck.java). public class ModelDuck extends Duck { public ModelDuck() { flyBehavior = new FlyNoWay(); quackBehavior = new Quack(); } public void display() { System.out.println(“I’m a model duck”); } }
//Make a new FlyBehavior type (FlyRocketPowered.java). public class FlyRocketPowered implements FlyBehavior { public void fly() { System.out.println(“I’m fl ying with a rocket!”); } }
//Change the test class (MiniDuckSimulator.java), add the //ModelDuck, and make the ModelDuck rocket-enabled. public class MiniDuckSimulator { public static void main(String[] args) { Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); Duck model = new ModelDuck(); model.performFly(); model.setFlyBehavior(new FlyRocketPowered()); model.performFly(); } }