策略模式
定义一系列的算法,每个单独封装。
策略模式中,需要创建一个表示各种策略的对象和一个随着策略对象改变而改变的Context对象。策略对象改变Context对象的算法。
类图关系
策略类
package com.alphajuns.strategy; public abstract class Strategy { public abstract void method(); }
策略A
package com.alphajuns.strategy; public class StrategyImplA extends Strategy { @Override public void method() { System.out.println("策略A"); } }
策略B
package com.alphajuns.strategy; public class StrategyImplB extends Strategy { @Override public void method() { System.out.println("策略B"); } }
策略C
package com.alphajuns.strategy; public class StrategyImplC extends Strategy { @Override public void method() { System.out.println("策略C"); } }
环境类
package com.alphajuns.strategy; public class Context { Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void doMethod() { strategy.method(); } }
测试类
package com.alphajuns.strategy; import org.junit.Test; public class StrategyTest { public static void main(String[] args) { Context context = new Context(new StrategyImplA()); context.doMethod(); context = new Context(new StrategyImplB()); context.doMethod(); context = new Context(new StrategyImplC()); context.doMethod(); } }