策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
这是一个比较简单的模式,核心的思想就是将应用中的变化之处独立出来,这样就可以避免继承而使得算法分散在各个子类中,从而减少维护所带来的开销。更多的利用组合而不是继承会使得我们的代码更加的灵活。
这是一个比较简单的模式,核心的思想就是将应用中的变化之处独立出来,这样就可以避免继承而使得算法分散在各个子类中,从而减少维护所带来的开销。更多的利用组合而不是继承会使得我们的代码更加的灵活。
package org.headfirst.strategy;
public abstract class Duck {
protected FlyBehavior flyBehavior = null;
// The ducks will own several different fly behaviors.
public void performFly() {
if (flyBehavior != null)
flyBehavior.fly();
}
// The method that will not be changed in the underlying sub classes.
public void swim() {
System.out.println("I'm swimming");
}
}
package org.headfirst.strategy;
public class GreenHeadDuck extends Duck {
public GreenHeadDuck() {
this.flyBehavior = new FlyWithWing();
}
// The Fly Behavior will be changed during runtime.
public synchronized void setFlyBehavior(FlyBehavior a) {
this.flyBehavior = a;
}
public static void main(String[] args) {
GreenHeadDuck ghduck = new GreenHeadDuck();
ghduck.swim();
ghduck.performFly();
ghduck.setFlyBehavior(new CanNotFly());
ghduck.performFly();
}
}
package org.headfirst.strategy;
public interface FlyBehavior {
public void fly();
}
package org.headfirst.strategy;
public class FlyWithWing implements FlyBehavior {
public void fly() {
System.out.println("I'm flying with wings");
}
}
package org.headfirst.strategy;
public class CanNotFly implements FlyBehavior {
public void fly() {
System.out.println("I can't fly");
}
}