C# 设计模式(7)适配器模式
适配器模式
1. 类适配器 (通过继承)
2. 对象适配器 (通过组合)
组合优于继承
数据库适配,代码实现:
原始类 Sql server /MySql
namespace AdapterPattern { interface IHelper { void Add<T>(); void Delete<T>(); void Update<T>(); void Query<T>(); } public class SqlHelper:IHelper { public void Add<T>() { Console.WriteLine($"{this.GetType().Name} Add Data"); } public void Delete<T>() { Console.WriteLine($"{this.GetType().Name} Delete Data"); } public void Update<T>() { Console.WriteLine($"{this.GetType().Name} Update Data"); } public void Query<T>() { Console.WriteLine($"{this.GetType().Name} Query Data"); } } public class MySqlHelper:IHelper { public void Add<T>() { Console.WriteLine($"{this.GetType().Name} Add Data"); } public void Delete<T>() { Console.WriteLine($"{this.GetType().Name} Delete Data"); } public void Update<T>() { Console.WriteLine($"{this.GetType().Name} Update Data"); } public void Query<T>() { Console.WriteLine($"{this.GetType().Name} Query Data"); } } }
适配Redis (原始Redis/Redis类适配/Redis对象适配)
public class RedisHelper { public void AddRedis<T>() { Console.WriteLine($"{this.GetType().Name} Add Data"); } public void DeleteRedis<T>() { Console.WriteLine($"{this.GetType().Name} Delete Data"); } public void UpdateRedis<T>() { Console.WriteLine($"{this.GetType().Name} Update Data"); } public void QueryRedis<T>() { Console.WriteLine($"{this.GetType().Name} Query Data"); } } public class RedisHelperClass:RedisHelper,IHelper { public void Add<T>() { base.AddRedis<T>(); } public void Delete<T>() { base.DeleteRedis<T>(); } public void Update<T>() { base.UpdateRedis<T>(); } public void Query<T>() { base.QueryRedis<T>(); } } public class RedisHelperObject:IHelper { private readonly RedisHelper _redisHelper; public RedisHelperObject(RedisHelper redisHelper) { _redisHelper = redisHelper; } public void Add<T>() { _redisHelper.AddRedis<T>(); } public void Delete<T>() { _redisHelper.DeleteRedis<T>(); } public void Update<T>() { _redisHelper.UpdateRedis<T>(); } public void Query<T>() { _redisHelper.QueryRedis<T>(); } }
代码调用:
class Program { static void Main(string[] args) { SqlHelper sqlHelper = new SqlHelper(); sqlHelper.Add<Program>(); sqlHelper.Delete<Program>(); sqlHelper.Update<Program>(); sqlHelper.Query<Program>(); MySqlHelper mySqlHelper = new MySqlHelper(); mySqlHelper.Add<Program>(); mySqlHelper.Delete<Program>(); mySqlHelper.Update<Program>(); mySqlHelper.Query<Program>(); RedisHelperClass redisHelperClass = new RedisHelperClass(); redisHelperClass.Add<Program>(); redisHelperClass.Delete<Program>(); redisHelperClass.Update<Program>(); redisHelperClass.Query<Program>(); RedisHelperObject redisHelperObject = new RedisHelperObject(new RedisHelper()); redisHelperObject.Add<Program>(); redisHelperObject.Delete<Program>(); redisHelperObject.Update<Program>(); redisHelperObject.Query<Program>(); } }
结果: