首先上一張策略模式的基本類圖:java
上面的這張圖就是策略模式的基本類圖,那麼咱們能夠看出策略模式其實和簡單工廠模式很是像,可是仍是有點區別的,簡單工廠模式中是採用工廠類來解決來建立,下降代碼的耦合性的,那麼策略模式呢?算法
策略模式通常用在封裝一些(可是不侷限)算法,在某一個功能上有不一樣的算法須要實現,好比排序(冒泡排序,快速排序,插入排序等)設計模式
那麼如今來看看具體策略模式是怎麼下降代碼的耦合性的:ide
public abstract class Strategy { public abstract void algorithmInterface();//抽象算法 }
public class StrategyA extends Strategy { public void algorithmInterface() { System.out.println("算法A實現"); } }
public class StrategyB extends Strategy { @Override public void algorithmInterface() { System.out.println("算法B實現"); } }
public class StrategyC extends Strategy { @Override public void algorithmInterface() { System.out.println("算法C實現"); } }
public class Context { public Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy;//初始化傳入具體的算法對象 } //根據具體的算法對象建立具體的算法 public void contextInterface(){ strategy.algorithmInterface(); } }
public class StrategyMain { public static void main(String[] args){ //建立算法A Context context = new Context(new StrategyA()); context.contextInterface();//算法A實現 //建立算法B context = new Context(new StrategyB()); context.contextInterface();//算法B實現 //建立算法C context = new Context(new StrategyC()); context.contextInterface();//算法C實現 } }
那麼經過這個簡單的策略模式的實現咱們能看出,當咱們在客戶端使用某一個定義好的算法的時候咱們不須要去管其餘的類,咱們只須要經過上下文(Context)這個類,傳入一個實體對象就能夠建立想要使用的算法,經過這樣的手段來下降程序的耦合性。學習
這個只是簡單的實例,也是策略模式的基本模型。
在咱們的使用過程當中,咱們能夠和其餘設計模式一塊兒使用,也就是綜合運用的體現。this
記錄學習的每一步,記錄每一步的成長!!!!設計