策略模式结合Map 重构 if else语句 patternstrategyjava
程序员文章站
2022-07-15 09:12:46
...
package com.bruce.pattern.strategy; import com.bruce.pattern.strategy.behavior.FlyBehavior; import com.bruce.pattern.strategy.behavior.QuackBehavior; public abstract class Duck { QuackBehavior quackBehavior; FlyBehavior flyBehavior; public abstract void display(); public void performFly() { flyBehavior.fly(); } public void performQuack() { quackBehavior.quack(); } public void setQuackBehavior(QuackBehavior quackBehavior) { this.quackBehavior = quackBehavior; } public void setFlyBehavior(FlyBehavior flyBehavior) { this.flyBehavior = flyBehavior; } }
package com.bruce.pattern.strategy; public class MallardDuck extends Duck { @Override public void display() { System.out.println("This is mallardDuck... "); } }
public interface FlyBehavior { void fly(); }
public class FlyWithWings implements FlyBehavior { @Override public void fly() { System.out.println("Flying with wings!"); } }
public class FlyNoWay implements FlyBehavior { @Override public void fly() { System.out.println("Flying no way...."); } }
package com.bruce.pattern.strategy; import java.util.HashMap; import java.util.Map; import com.bruce.pattern.strategy.behavior.*; public class Client { /** * @param args */ public static void main(String[] args) { Duck duck = new MallardDuck(); for(int i = 0;i<2;i++) { if(i == 0) { duck.setFlyBehavior(new FlyWithWings()); } else { duck.setFlyBehavior(new FlyNoWay()); } fly(duck); } Map<String, FlyBehavior> map = new HashMap<String, FlyBehavior>(); map.put("0", new FlyWithWings()); map.put("1", new FlyNoWay()); for(int i = 0;i<2;i++) { FlyBehavior flyBehavior = map.get(Integer.toString(i)); duck.setFlyBehavior(flyBehavior); fly(duck); } } public static void fly(Duck duck) { duck.performFly(); } }
运行结果:
Flying with wings! Flying no way.... Flying with wings! Flying no way....
看到有帖子讨论这个,策略+表驱动法(Map),不错,哪天再结合工厂方法写个重构的例子,总结以后使用。
上一篇: Map to List