适配器模式

将一个类的接口转换成客户希望的另外一个接口,适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

新类继承了RedisHelper,但是如果RedisHelper中有我们不想要的方法,也必须继承。此处RedisHelper是接口。

/// <summary>
    /// 类适配器:新建的对象需要继承接口
    /// </summary>
    public class RedisHelperInherit : ReidsHelper, IHelper
    {
        /// <summary>
        /// 对新增的Redis进行实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void Add<T>() {
            base.AddRedis();
        }
        public void Del<T>()
        {
            base.DelRedis();
        }
        public void Update<T>()
        {
            base.UpdateRedis();
        }
        public void Query<T>()
        {
            base.QueryRedis();
        }
    }
/// <summary>
    /// 对象适配器模式,当我的数据库发生变化的时候(此处新增Redis),但是对象中的方法名称和Sql中的方法名称不一样,之前在IHelper中声明的接口在Redis中不存在
    /// 那么就需要重新创建一个类,该类会满足IHelper的接口实现,在实现的方法中去调用Redis提供的方法。
    /// </summary>
    public class RedisHelperCombination : IHelper
    {
        //1、字段属性方式组合, 默认构造函数,强烈入侵,且是写死的
        RedisHelper _redisHelper = new RedisHelper();//组合进来

        //2、构造函数方式组合,实例化会传入,但是对象是可以选择的
        RedisHelper _redisHelperCtor = null;
        public RedisHelperCombination(RedisHelper redisHelper)
        {
            this._redisHelperCtor = redisHelper;
        }

        //3、方法方式组合,对象可以选择,而且可有可无
        public void AddRedisHelper(RedisHelper redisHelper)
        {
            this._ReidsHelperCtor = redisHelper;
        }

        public void Add() {
           return _redisHelperCtor.Add();
        }
        public void Del() {
            return _redisHelperCtor.Del();
        }
        public void Update() {
            return _redisHelperCtor.Update();
        }
        public void Query() {
            return _redisHelperCtor.Query();
        }
    }
原文地址:https://www.cnblogs.com/vichin/p/11589914.html