场景如下:三个妙计,一个锦囊(Context),一个赵云(使用者),锦囊中的妙计是小亮给的,赵云是个执行者,从锦囊中取出妙计,执行然后获胜。三个妙计是同一个东西那咱就写个接
package com.fc.strategy; public interface IStrategy { public void operate(); }
然后有三个妙计,一次实现这个接口:
package com.fc.strategy; public class First implements IStrategy{ @Override public void operate() { System.out.println("这是第一个锦囊"); } }
package com.fc.strategy; public class Seconde implements IStrategy{ @Override public void operate() { System.out.println("这是第2个锦囊"); } }
package com.fc.strategy; public class Third implements IStrategy{ @Override public void operate() { System.out.println("这是第3个锦囊"); } }
妙计既然有了那我们再来个锦囊来装这些妙计:
package com.fc.strategy; public class MyContext { private IStrategy strategy; public MyContext(IStrategy strategy) { this.strategy = strategy; } public void opt(){ this.strategy.operate(); } }
好了现在精囊妙计已经起了,下面该赵云登场了,噔噔蹬蹬:
package com.fc.strategy; public class Zhaoyun { public static void main(String[] args) { MyContext context; // 第一个 context = new MyContext(new First()); context.opt(); // 第二个 context = new MyContext(new Seconde()); context.opt(); // 第三个 context = new MyContext(new Third()); context.opt(); } }
策略模式体现了高内聚低耦合的特性
时间: 2024-10-13 16:32:30