StrategyPattern (策略模式)
/** * 策略模式 * @author TMAC-J * 根据环境的不同选择不同的策略,把策略用接口抽象出来 */ public class StrategyPattern { interface Strategy{ void operate(); } public class StrategyA implements Strategy{ @Override public void operate() { System.out.println("策略A"); } } public class StrategyB implements Strategy{ @Override public void operate() { System.out.println("策略B"); } } public class Context{ private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void operate(){ strategy.operate(); } } public void test(){ Context context1 = new Context(new StrategyA()); context1.operate(); Context context2 = new Context(new StrategyB()); context2.operate(); } }