- public abstract class Duck {
- FlyBehavior flyBehavior;
- QuackBehavior quackBehavior;
- public Duck() {
- }
- public void setFlyBehavior (FlyBehavior fb) {
- flyBehavior = fb;
- }
- public void setQuackBehavior(QuackBehavior qb) {
- quackBehavior = qb;
- }
- 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 interface FlyBehavior {
- public void fly();
- }
- public interface QuackBehavior {
- public void quack();
- }
- public class FlyWithWings implements FlyBehavior {
- public void fly() {
- System.out.println("I'm flying!!");
- }
- }
- public class RedHeadDuck extends Duck {
- public RedHeadDuck() {
- flyBehavior = new FlyWithWings();//子类中改变实现,且互不影响。
- quackBehavior = new Quack();
- }
- public void display() {
- System.out.println("I'm a real Red Headed duck");
- }
- }
测试代码如下:
RedHeadDuck redHeadDuck = new RedHeadDuck();
redHeadDuck.performFly();
redHeadDuck.display();
输出结果:
I'm flying!!
I'm a real Red Headed duck
下面我们可以实现其他飞的方式,例如乘火箭
- public class FlyRocketPowered implements FlyBehavior {
- public void fly() {
- System.out.println("I'm flying with a rocket");
- }
- }
测试代码:
RedHeadDuck redHeadDuck = new RedHeadDuck();
redHeadDuck.setFlyBehavior(new FlyRocketPowered());
redHeadDuck.display();
redHeadDuck.performFly();
输出结果:
I'm a real Red Headed duck
I'm flying with a rocket
小结:
可见策略模式定义了算法,将他们分别封装,他们之间可以相互替换。(例如:FlyWithWings和FlyRocketPowered)
这样每个实现都相互不影响。