策略模式
策略模式定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的用户
UML图
代码
-
Context
package design_patterns.strategy; public interface Strategy { void execute(); }
-
Strategy
package design_patterns.strategy; public interface Strategy { void execute(); }
-
StrategyA
package design_patterns.strategy; public class StrateA implements Strategy { @Override public void execute() { System.out.println("执行策略A"); } }
-
StrategyB
package design_patterns.strategy; public class StrateB implements Strategy { @Override public void execute() { System.out.println("执行策略B"); } }
-
StrategyC
package design_patterns.strategy; public class StrateC implements Strategy { @Override public void execute() { System.out.println("执行策略C"); } }
-
client
package design_patterns.strategy; public class Client { public static void main(String[] args) { String type = "A"; Context context = null; switch (type){ case "A": context = new Context(new StrateA()); break; case "B": context = new Context(new StrateB()); break; case "C": context = new Context(new StrateC()); break; default: break; } if(context != null){ context.execute(); } } }
策略模式和简单工厂结合
-
修改Context代码
package design_patterns.strategy; public class FactoryContext { private Strategy strategy ; public FactoryContext(String type) { switch (type){ case "A": strategy = new StrateA(); break; case "B": strategy = new StrateB(); break; case "C": strategy = new StrateC(); break; default: break; } } public void execute(){ if (this.strategy != null){ this.strategy.execute(); }else { System.out.println("error"); } } }
-
客户端代码
package design_patterns.strategy; public class Client2 { public static void main(String[] args) { String type = "A"; FactoryContext factoryContext = new FactoryContext(type); factoryContext.execute(); } }
策略模式总结
策略模式是定义一些列算法的方法,从概念上看,所有这些算法完成的都是相同的工作,只是实现不同。它可以以相同的的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合