设计原则:
1. 找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起
2. 针对接口编程,而不是针对试下编程
3. 多用组合,少用继承
策略模式:
定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。
Duck问题:
public abstract class Duck {
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;
//more...
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 void setFlyBehavior(FlyBehavior fb){
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb){
quackBehavior = qb;
}
}
public interface FlyBehavior {
public void fly();
}
public interface QuackBehavior {
public void quack();
}
public class FlyWitheWings implements FlyBehavior {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("I am flying!!");
}
}
public class FlyNoWay implements FlyBehavior {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("I cannot fly...");
}
}
public class FlyRocketPowered implements FlyBehavior {
@Override
public void fly() {
System.out.println("I am flying with a rocket!");
}
}
public class Quack implements QuackBehavior {
@Override
public void quack() {
// TODO Auto-generated method stub
System.out.println("Quack");
}
}
public class MuteQuack implements QuackBehavior {
@Override
public void quack() {
// TODO Auto-generated method stub
System.out.println("<<Silence>>");
}
}
public class Squeek implements QuackBehavior {
@Override
public void quack() {
// TODO Auto-generated method stub
System.out.println("Squeak");
}
}
public class MallardDuck extends Duck{
public MallardDuck(){
quackBehavior = new Quack();
flyBehavior = new FlyWitheWings();
}
@Override
public void display() {
// TODO Auto-generated method stub
}
}
public class ModelDuck extends Duck {
public ModelDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Quack();
}
@Override
public void display() {
System.out.println("I am a model duck");
}
}
//测试类
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();
}
}
输出:
Quack
I am flying!!
I cannot fly...
I am flying with a rocket!