23種設計模式,天天一種設計模式(2)

建立型模式,共五種:工廠方法模式抽象工廠模式單例模式建造者模式原型模式redis

結構型模式,共七種: 適配器模式裝飾器模式代理模式外觀模式橋接模式組合模式享元模式
行爲型模式,共十一種: 策略模式模板方法模式觀察者模式迭代子模式責任鏈模式命令模式備忘錄模式狀態模式訪問者模式中介者模式解釋器模式
 
今天說結構型設計模式裏的 適配器模式
 
結構型設計模式,其實就是經過封裝或者組合的方式,優化改進代碼結構
 
目的:新接口和老接口之間進行適配
途徑:類適配器模式和對象適配器模式
 
 
使用場景
一、有一個接口IHelper,裏邊有四個方法,增刪改查
1     public interface IHelper 2  { 3         void Add<T>(); 4         void Delete<T>(); 5         void Update<T>(); 6         void Query<T>(); 7     }

二、子類MysqlHelper、OracleHelper、SqlserverHelper繼承了IHelper,並實現IHelper接口sql

三、如今有類RedisHelper,他有四個方法增刪改查設計模式

 1         public void AddRedis<T>()  2  {  3             Console.WriteLine("This is {0} Add", this.GetType().Name);  4  }  5         public void DeleteRedis<T>()  6  {  7             Console.WriteLine("This is {0} Delete", this.GetType().Name);  8  }  9         public void UpdateRedis<T>() 10  { 11             Console.WriteLine("This is {0} Update", this.GetType().Name); 12  } 13         public void QueryRedis<T>() 14  { 15             Console.WriteLine("This is {0} Query", this.GetType().Name); 16         }

四、問題來了,發現RedisHelper方法跟IHelper方法不太適配,爲了跟IHelper適配,就須要適配器模式函數

五、這裏適配器模式有兩種學習

①、類適配器模式優化

  新建一個RedisHelperClass類來繼承RedisHelper和IHelper,此時RedisHelperClass至關於適配器this

 1     public class RedisHelperClass : RedisHelper, IHelper  2  {  3         public void Add<T>()  4  {  5             base.AddRedis<T>();  6  }  7 
 8         public void Delete<T>()  9  { 10             base.DeleteRedis<T>(); 11  } 12 
13         public void Update<T>() 14  { 15             base.UpdateRedis<T>(); 16  } 17 
18         public void Query<T>() 19  { 20             base.QueryRedis<T>(); 21  } 22     }

②、對象適配器模式RedisHelperObject,經過構造函數傳遞一個RedisHelperspa

 1     public class RedisHelperObject : IHelper  2  {  3         //private RedisHelper _RedisHelper = new RedisHelper();
 4         private RedisHelper _RedisHelper = null;  5         public RedisHelperObject(RedisHelper redisHelper)  6  {  7             this._RedisHelper = redisHelper;  8  }  9 
10         public RedisHelperObject() 11  { 12             this._RedisHelper = new RedisHelper(); 13  } 14 
15         public void Add<T>() 16  { 17             this._RedisHelper.AddRedis<T>(); 18  } 19 
20         public void Delete<T>() 21  { 22             this._RedisHelper.DeleteRedis<T>(); 23  } 24 
25         public void Update<T>() 26  { 27             this._RedisHelper.UpdateRedis<T>(); 28  } 29 
30         public void Query<T>() 31  { 32             this._RedisHelper.QueryRedis<T>(); 33  } 34     }

 

總結:適配器模式,有類適配器模式和對象適配器模式,在上面的例子裏RedisHelperClass和RedisHelperObject都充當了適配器的角色,前者經過繼承的關係,使RedisHelperClass和MysqlHelper、OracleHelper、SqlserverHelper進行了適配,後者經過組合對象,進行了適配設計

 

以上是本人經過學習,去理解和總結的,若是有什麼不當之處,還請大牛指正!代理

相關文章
相關標籤/搜索