设计模式---适配器模式

设计模式---适配器模式

前言

上一次谈设计模式,我谈到了装饰者模式,今天我要谈与之很相似的另一个结构型的设计模式:适配器模式。最后还会结合外观模式进行适当点评

UML类图

设计模式---适配器模式

角色构成

  • Target,面向用户使用的接口定义
  • Adapter,适配器,将被适配接口转换为用户需要的Target接口
  • Adaptee,需要被适配的现有接口

代码

待适配对象

namespace Adapter
{
    public class Adaptee
    {
        public void AdapteeOperation()
        {
            Console.WriteLine("Adaptee Operation");
        }
    }
}

用户接口

namespace Adapter
{
    public interface Target
    {
        void UserOperation();
    }
}

适配器

namespace Adapter
{
    public class Adapter : Target
    {
        private Adaptee _adaptee = new Adaptee();

        public void UserOperation()
        {
            this._adaptee.AdapteeOperation();
        }
    }
}

用户调用代码

namespace Adapter
{
    class Program
    {
        static void Main(string[] args)
        {
            Target target = new Adapter();

            target.UserOperation();

            Console.ReadKey();
        }
    }
}

使用场景

可参见ADO.NET中的抽象DataAdapter以及具体的SqlDataAdapter、OracleDataAdapter的设计

结构型设计模式大比拼

  共同点 不同点
装饰者模式 对象包装 不改变接口,加入新的职责
适配器模式   不改变职责,改变接口
外观模式   简化高层接口,统一调用