由於最近在研究學習設計模式,我會用自己的理解方式來表述對設計模式的學習和認識,通過最常用、好記的案例來記住和使用設計模式,希望對設計代碼方面有所提高和改進。
一.應用背景
在軟件開發中常常遇到這種情況,實現某一個功能有多種算法或者策略,我們可以根據應用場景的不同選擇不同的算法或者策略來完成該功能。把一個類(A)中經常改變或者將來可能改變的部分提取出來,作為一個接口(B),然后在類(A)中包含這個接口(B),這樣類(A)的實例在運行時就可以隨意調用實現了這個接口的類(C)的行為。比如定義一系列的算法,把每一個算法封裝起來, 並且使它們可相互替換,使得算法可獨立於使用它的客戶而變化。這就是策略模式。
二.優、缺點
優點:
1、可以動態的改變對象的行為
缺點:
1、客戶端必須知道所有的策略類,並自行決定使用哪一個策略類
2、策略模式將造成產生很多策略類
三.組成
1.運行環境類:Strategy
這個策略模式運行的環境,其實也就是在哪里使用
2.應用場景類:Person
這個就是客戶端訪問的類,也就是該類的對象所持有的策略
3具體策略類:Car
具體實現策略類
4..抽象策略類:CarFunction
根據不同的需求,產生不同的策略或算法的接口
四.代碼實現
1.抽象策略類:CarFunction
1 package com.design.strategy; 2 /** 3 * @ClassName : CarFunction 4 * @Description : 策略類 5 * 6 */ 7 8 public interface CarFunction { 9 void run(); //每輛車有不同的行駛方法 10 }
2.具體策略父類
1 package com.design.strategy; 2 /** 3 * 4 * @ClassName : Car 5 * @Description : 每個車都具有的相同的屬性和行為 6 * 7 */ 8 public class Car implements CarFunction { 9 protected String name; //車名字 10 protected String color; //車顏色 11 12 13 public Car(String name, String color) { 14 this.name = name; 15 this.color = color; 16 } 17 18 @Override 19 public void run() { 20 System.out.println(color +" " + name +"在行駛。。。"); 21 } 22 23 }
3.具體策略實現子類
1 package com.design.strategy; 2 /** 3 * 4 * @ClassName : SmallCar 5 * @Description : 具體策略實現子類 6 * 7 */ 8 public class SmallCar extends Car { 9 10 public SmallCar(String name, String color) { 11 super(name, color); 12 } 13 14 public void run() { 15 System.out.println(color +" " + name +"在高速的行駛。。。"); 16 } 17 18 }
1 package com.design.strategy; 2 3 public class BussCar extends Car{ 4 5 public BussCar(String name, String color) { 6 super(name, color); 7 } 8 9 public void run() { 10 System.out.println(color +" " + name +"在緩慢的行駛。。。"); 11 } 12 }
4.應用場景類
1 package com.design.strategy; 2 /** 3 * 4 * @ClassName : Person 5 * @Description : 應用場景類 6 * 7 */ 8 public class Person { 9 private String name; //姓名 10 private Integer age; //年齡 11 private Car car; //擁有車 12 13 public void driver(Car car){ 14 System.out.print(name +" "+ age+" 歲 "+" 開着"); 15 car.run(); 16 } 17 18 public Person(String name,Integer age) { 19 this.name=name; 20 this.age=age; 21 } 22 23 }
5.運行環境類:Strategy
1 package com.design.strategy; 2 /** 3 * 4 * @ClassName : Strategy 5 * @Description : 運行環境類:Strategy 6 * @date : 2017年12月9日 上午11:43:58 7 * 8 */ 9 public class Strategy { 10 public static void main(String[] args) { 11 Car smallCar = new SmallCar("路虎","黑色"); 12 Car bussCar = new BussCar("公交車","白色"); 13 Person p1 = new Person("小明", 20); 14 p1.driver(smallCar); 15 p1.driver(bussCar); 16 } 17 } 18 19 運行結果: 20 小明 20 歲 開着黑色 路虎在高速的行駛。。。 21 小明 20 歲 開着白色 公交車在緩慢的行駛。。。
五.總結
策略模式可以理解為老司機開車,但是他今天想到路虎,明天想開奔馳。。。,針對他不同的需求,來產生不同的應對策略,好記一點就是:老司機開車!!! 哈哈。。。
六.延伸
同樣也可以延伸到商家搞活動,消費多少元減50之類的應用場景,等等,舉一反三,會發現生活中有很多的例子都是用到了策略模式。