目录
策略模式:
策略模式优点:
策略模式应用:
策略实例:
上述代码 GitHub 地址:https://github.com/baicun/designPatterns
分别封装行为接口,实现算法族,超类里放行为接口对象,在子类中具体设定行为对象。原则是分离变化部分,封装接口,基于接口编程各种功能。此模式让行为算法的变化独立于算法的使用者。
新增行为简单,行为类更好的复用,组合更方便。
Arrays.sort();
Collections.sort();
类图:
定义抽象类:
public abstract class Duck { FlyBehavior mFlyBehavior; QuackBehavior mQuackBehavior; public Duck() { } public void Fly() { mFlyBehavior.fly(); } public void Quack() { mQuackBehavior.quack(); } public abstract void display(); public void SetQuackBehavoir(QuackBehavior qb) { mQuackBehavior = qb; } public void SetFlyBehavoir(FlyBehavior fb) { mFlyBehavior = fb; } public void swim() { System.out.println("~~im swim~~"); } }抽象类的俩个子类实现:
public class GreenHeadDuck extends Duck { public GreenHeadDuck() { mFlyBehavior = new GoodFlyBehaviorImpl(); mQuackBehavior = new GaGaQuackBehaviorImpl(); } @Override public void display() { System.out.println("**GreenHead**"); } } public class RedHeadDuck extends Duck { public RedHeadDuck() { mFlyBehavior = new BadFlyBehaviorImpl(); mQuackBehavior = new GeGeQuackBehaviorImpl(); } @Override public void display() { System.out.println("**RedHead**"); } }测试类:
public class mainTest { public static void main(String[] args){ Duck greenDuck = new GreenHeadDuck(); greenDuck.display(); greenDuck.Fly(); greenDuck.Quack(); greenDuck.swim(); Duck redDuck = new RedHeadDuck(); redDuck.display(); redDuck.Fly(); redDuck.Quack(); redDuck.swim(); redDuck.SetFlyBehavoir(new NoFlyBehaviorImpl()); //行为对象 redDuck.Fly(); } }