目标角色
public interface IHelper { void Add<T>(); void Delete<T>(); void Update<T>(); void Query<T>(); }
被适配器角色
sqlserver、mysql、redis
适配器角色
SqlServerHelper
public class SqlServerHelper : IHelper { public void Add<T>() { Console.WriteLine("This is {0} Add", this.GetType().Name); } public void Delete<T>() { Console.WriteLine("This is {0} Delete", this.GetType().Name); } public void Update<T>() { Console.WriteLine("This is {0} Update", this.GetType().Name); } public void Query<T>() { Console.WriteLine("This is {0} Query", this.GetType().Name); } }
MysqlHelper
public class MysqlHelper : IHelper { public void Add<T>() { Console.WriteLine("This is {0} Add", this.GetType().Name); } public void Delete<T>() { Console.WriteLine("This is {0} Delete", this.GetType().Name); } public void Update<T>() { Console.WriteLine("This is {0} Update", this.GetType().Name); } public void Query<T>() { Console.WriteLine("This is {0} Query", this.GetType().Name); } }
对于一些第三方的组件方法,它里面已有类似的方法,这个时候我们可以采取 继承或 组合的方式,来做适配
/// <summary> /// 第三方提供的 openstack servicestack /// 不能修改 /// </summary> public class RedisHelper { public RedisHelper() { Console.WriteLine($"构造RedisHelper"); } public void AddRedis<T>() { Console.WriteLine("This is {0} Add", this.GetType().Name); } public void DeleteRedis<T>() { Console.WriteLine("This is {0} Delete", this.GetType().Name); } public void UpdateRedis<T>() { Console.WriteLine("This is {0} Update", this.GetType().Name); } public void QueryRedis<T>() { Console.WriteLine("This is {0} Query", this.GetType().Name); } }
类适配器,通过继承的方式,在它上面实现目标IHelper
/// <summary> /// 类适配器 /// </summary> public class RedisHelperInherit : RedisHelper, IHelper { public RedisHelperInherit() { Console.WriteLine($"构造{this.GetType().Name}"); } public void Add<T>() { base.AddRedis<T>(); } public void Delete<T>() { base.DeleteRedis<T>(); } public void Query<T>() { base.QueryRedis<T>(); } public void Update<T>() { base.UpdateRedis<T>(); } }
对象适配器,通过组合的方式,在它上面实现目标IHelper
public class RedisHelperObject : IHelper { public RedisHelperObject() { Console.WriteLine($"构造{this.GetType().Name}"); } //属性注入 声明写死 private RedisHelper _RedisHelper = new RedisHelper(); ////构造函数 可以替换(需要抽象) public RedisHelperObject(RedisHelper redisHelper) { this._RedisHelper = redisHelper; } ////方法注入 可以替换(需要抽象) public void SetObject(RedisHelper redisHelper) { this._RedisHelper = redisHelper; } public void Add<T>() { this._RedisHelper.AddRedis<T>(); } public void Delete<T>() { this._RedisHelper.DeleteRedis<T>(); } public void Query<T>() { this._RedisHelper.QueryRedis<T>(); } public void Update<T>() { this._RedisHelper.UpdateRedis<T>(); } }
运行测试
{ //继承 既满足现有的规范调用,又没有修改RedisHelper //类适配器模式 IHelper helper = new RedisHelperInherit(); helper.Add<Program>(); helper.Delete<Program>(); helper.Update<Program>(); helper.Query<Program>(); } { //组合 既满足现有的规范调用,又没有修改RedisHelper //对象适配器 IHelper helper = new RedisHelperObject(); helper.Add<Program>(); helper.Delete<Program>(); helper.Update<Program>(); helper.Query<Program>(); }