策略模式 |
通用类图的源码如下:
public interface IStrategy { //定义具体策略必须具有的方法 public void doSomething(); } public class ConcreteStrategy1 implements IStrategy{ public void doSomething(){ System.out.println("this is a concreteStrategy"); } } public class ConcreteStrategy2 implements IStrategy{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("This is concreteStrategy2"); } } public class Context { private IStrategy strategy = null; public Context(IStrategy strategy){ this.strategy = strategy; } public void doSomething(){ this.strategy.doSomething(); } } public class Client { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Context text = new Context(new ConcreteStrategy2()); text.doSomething(); text = new Context(new ConcreteStrategy1()); text.doSomething(); } }
策略模式的优缺点 |
策略模式的扩展(工厂方法模式+策略模式) |
首先策略枚举StrategyMan,负责对具体策略的映射,然后建立一个简单的工厂,根据策略管理类的枚举项创建一个策略对象,简单而实用,策略模式的缺陷得到了弥补。其通用类图如下:
public enum StrategyMan { Strategy1("com.strategy.ConcreteStrategy1"), Strategy2("com.strategy.ConcreteStrategy2"); String value = ""; private StrategyMan(String value){ this.value = value; } public String getValue(){ return this.value; } } public class StrategyFactory { public static IStrategy getStrategy(StrategyMan strategyman){ IStrategy strategy = null; try { strategy = (IStrategy) Class.forName(strategyman.getValue()).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return strategy; } } public class StrategyFacade { public void doSomething(String str){ StrategyMan sMan = null; if(str.equalsIgnoreCase("Strategy1")){ sMan = StrategyMan.Strategy1; }else if(str.equalsIgnoreCase("Strategy2")){ sMan = StrategyMan.Strategy2; } IStrategy strategy = StrategyFactory.getStrategy(sMan); Context context = new Context(strategy); context.doSomething(); } } public class Client { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub StrategyFacade sFacade = new StrategyFacade(); sFacade.doSomething("Strategy1"); } }
原文:http://www.cnblogs.com/zhanglei93/p/6081019.html