package com.ayo.strategy;/** * 策略模式上下文 */public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void test(){ strategy.say(); } public static void main(String[] args) { Context context = new Context(new StrategyC()); context.test(); }}
package com.ayo.strategy;/** * 策略接口 */public interface Strategy { /** * 策略方法 */ public void say();}
package com.ayo.strategy;/** * 策略A */public class StrategyA implements Strategy { @Override public void say() { System.out.println("我选A!"); }}
package com.ayo.strategy;/** * 策略C */public class StrategyC implements Strategy { @Override public void say() { System.out.println("我选C!"); }}
package com.ayo.strategy;/** * 策略B */public class StrategyB implements Strategy { @Override public void say() { System.out.println("我选B!"); }}