Head First设计模式之策略模式
1 定义
策略模式定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户
2 设计原则
1 找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要的变化的代码混合在一起;
2 针对接口编程,而不是针对实现编程;
3 多用组合,少用继承。
3 代码实现
1 飞行父类
package Strategy;
public interface FlyBehavior {
public void fly();
}
飞行的两个具体实现类
package Strategy;
public class FlyNoWay implements FlyBehavior{
@Override
public void fly() {
System.out.println("===我飞不起来===");
}
}
package Strategy;
public class FlyWithWings implements FlyBehavior{
@Override
public void fly() {
System.out.println("===我能用翅膀飞===");
}
}
2 叫的父类
package Strategy;
public interface QuackBehavior {
public void quack();
}
叫的实现类
package Strategy;
public class Quack implements QuackBehavior{
@Override
public void quack() {
System.out.println("====我也会呱呱叫====");
}
}
package Strategy;
public class Squeak implements QuackBehavior{
@Override
public void quack() {
System.out.println("====我不会呱呱叫====");
}
}
3 鸭子父类
package Strategy;
public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public abstract void display();
public void performFly(){
flyBehavior.fly();
}
public void performQuack(){
quackBehavior.quack();
}
public void setFlyBehavior(FlyBehavior flyBehavior) {
this.flyBehavior = flyBehavior;
}
public void setQuackBehavior(QuackBehavior quackBehavior) {
this.quackBehavior = quackBehavior;
}
}
鸭子的实现类
package Strategy;
public class ModelDuck extends Duck{
public ModelDuck(){
flyBehavior=new FlyNoWay();
quackBehavior=new Squeak();
}
@Override
public void display() {
System.out.println("===我是一只模型鸭===");
}
}
4 客户端
package Strategy;
public class MimiDuckSimulator {
public static void main(String args[]){
Duck model=new ModelDuck();
model.performFly();
model.performQuack();
System.out.println("------------------------");
model.setFlyBehavior(new FlyWithWings());
model.setQuackBehavior(new Quack());
model.performFly();
model.performQuack();
}
}