策略模式 |
通用類圖的源碼以下:html
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"); } }