策略模式,不讲过多的废话。咱们来直接看代码。java
一、咱们先定一个接口ide
package com.guoguo.celvemoshi; /** * 定义一个策略接口 * @author 蝈蝈 * */ public interface StrategyService { //定义一个可执行方法 public void execute(); }
二、策略的具体实现(java多态---不懂先去了解多态的使用)this
package com.guoguo.celvemoshi; /** * 第一个策略 * @author 蝈蝈 * */ public class CelveOneServiceImpl implements StrategyService{ @Override public void execute() { System.err.println("执行策略一"); } }
package com.guoguo.celvemoshi; /** * 第二个策略 * @author 蝈蝈 * */ public class CelveTwoServiceImpl implements StrategyService { @Override public void execute() { // TODO Auto-generated method stub System.err.println("执行策略二"); } }
package com.guoguo.celvemoshi; /** * 第三个策略 * @author 蝈蝈 * */ public class CelveThreeServiceImpl implements StrategyService { @Override public void execute() { // TODO Auto-generated method stub System.err.println("执行策略三"); } }
三、策略定好以后,须要有个地方存放这些策略,以便在不一样的状况下方便使用spa
package com.guoguo.celvemoshi; public class Context { private StrategyService straService; //定义构造方法 public Context(StrategyService straService){ this.straService = straService; } //定义一个执行方法,去执行对应的策略 public void execute() { this.straService.execute(); } }
四、策略的使用code
package com.guoguo.celvemoshi; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Context context; //在不一样的状况下使用不一样的策略,咱们先使用策略三 context = new Context(new CelveThreeServiceImpl()); context.execute(); // 在不一样的状况下使用不一样的策略,咱们先使用策略二 context = new Context(new CelveTwoServiceImpl()); context.execute(); // 在不一样的状况下使用不一样的策略,咱们先使用策略一 context = new Context(new CelveOneServiceImpl()); context.execute(); } }