首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

Head First Design Patterns 读后感3-谋略模式

2012-10-26 
Head First Design Patterns 读后感3-策略模式策略模式-定义了算法族,分别封装起来,让他们之间可以相互替

Head First Design Patterns 读后感3-策略模式
策略模式-定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。策略模式有点像调包计和偷梁换柱。
设计模式就是为了适应变化那些大师而想起来的,能适应变化的软件才能长命,人也一样,只有适应外界变化,方可生存。


package pattern;
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 setFlyBehavior(FlyBehavior fb) {
  flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
  quackBehavior = qb;
}
public void swim() {
  System.out.println("All ducks float,even decoys!");
}
}
interface FlyBehavior {
public void fly();
}
class FlyWithWings implements FlyBehavior {
public void fly() {
  System.out.println("I am flying!!");
}
}
class FlyNoWay implements FlyBehavior {
public void fly() {
  System.out.println("i can not flying !!");
}
}
class FlyRocketPowered implements FlyBehavior {
public void fly() {
  System.out.println("i am flying with a rocket!");
}
}
interface QuackBehavior {
public void quack();
}
class Quack implements QuackBehavior {
public void quack() {
  System.out.println("Quack");
}
}
class MuteQuack implements QuackBehavior {
public void quack() {
  System.out.println("<<>Silence>");
}
}
class Squeak implements QuackBehavior {
public void quack() {
  System.out.println("Squeak");
}
}
class MallardDuck extends Duck {
public MallardDuck() {
  quackBehavior = new Quack();
  flyBehavior = new FlyWithWings();
}
public void display() {
  System.out.println("i am a real Mallard duck");
}
}
class ModelDuck extends Duck {
public ModelDuck() {
  flyBehavior = new FlyNoWay();
  quackBehavior = new Quack();
}
public void display() {
  System.out.println("i am a model duck");
}
}
class MiniDuckSimulator {
public static void main(String[] args) {
  Duck mallard = new MallardDuck();
  mallard.performQuack();
  mallard.performFly();
  Duck model = new ModelDuck();
  model.performFly();
  model.performQuack();
  model.setFlyBehavior(new FlyWithWings());
  model.setQuackBehavior(new Squeak());
  model.performFly();
  model.performQuack();
}
}

热点排行