Head First 设计模式学习笔记 一 策略模式

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
这是一个比较简单的模式,核心的思想就是将应用中的变化之处独立出来,这样就可以避免继承而使得算法分散在各个子类中,从而减少维护所带来的开销。更多的利用组合而不是继承会使得我们的代码更加的灵活。
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");
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值