结构性设计模式-适配器模式(AdapterPattern)

把一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)

1.原有的代码

    /// </summary>
    public interface IHelper
    {
        void Add<T>();
    }
    public class SqlserverHelper : IHelper
    {
        public void Add<T>()
        {
            Console.WriteLine("This is {0} Add", this.GetType().Name);
        }
    }
    public class MysqlHelper : IHelper
    {
        public void Add<T>()
        {
            Console.WriteLine("This is {0} Add", this.GetType().Name);
        }
    }
	//使用
	IHelper helper=new MysqlHelper();
	helper.Add<T>();
	IHelper helper=new SqlserverHelper ();
	helper.Add<T>();

2.矛盾的产生

新增加了特殊实现,无妨遵循原来的IHelper

public class RedisHelper
{
    public void AddRedis<T>()
    {
        Console.WriteLine("This is {0} Add", this.GetType().Name);
    }
    public void SetTime(){
    }
}

3.解决

1.类适配器(继承)

 public class RedisHelperInherit : RedisHelper, IHelper
 {
      public RedisHelperInherit():base()//构造子类前 会先构造父类
      {
          Console.WriteLine($"构造RedisHelperInheritr");
      }

      public void Add<T>()
      {
          base.AddRedis<T>();
      }
}

继承过于侵入,比如RedisHelperInherit也会继承了SetTime,但不是此环境下需要用到的

2.对象适配器(组合)

 public class RedisHelperCombination : IHelper
 {
		/// <summary>
		/// 内置字段直接初始化---构造函数注入/方法注入
		/// </summary>
		private RedisHelper _RedisHelper = new RedisHelper();
		public RedisHelperCombination()
		{
		    Console.WriteLine($"构造RedisHelperInheritr");
		}
		
		//public RedisHelperCombinnation(IRedisHelper _RedisHelper)
		//{
		//    Console.WriteLine($"构造RedisHelperInheritr");
		//}
		
		public void Add<T>()
		{
		    this._RedisHelper.AddRedis<T>();
		}
}

4.总结

组合优于继承,优先选择 "2.对象适配器(组合)":
1 继承是强侵入性(有多余的东西) 
2 灵活性问题(组合是依赖抽象,继承是依赖细节的)
  既RedisHelper _RedisHelper = new RedisHelper();可以换成IOtherDB _RedisHelper =new RedisHelper()
3.命名约束:IHelperAdapter,MySqlHelperAdapter

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值