zoukankan      html  css  js  c++  java
  • 设计模式---适配器模式

    前言

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

    UML类图

    adapter

    角色构成

    • 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的设计

    结构型设计模式大比拼

      共同点 不同点
    装饰者模式 对象包装 不改变接口,加入新的职责
    适配器模式   不改变职责,改变接口
    外观模式   简化高层接口,统一调用
  • 相关阅读:
    2014华为员工年终奖及年薪盘点
    Gradle命令行黑魔法
    委托的那些事
    动态代理
    音乐播放
    Eclipse plugin web site 发布和版本更新
    JavaScript—之对象参数的引用传递
    Bootstrap 3 How-To #1 下载与配置
    代码审计和漏洞挖掘的思路
    核心C#
  • 原文地址:https://www.cnblogs.com/fecktty2013/p/designpatterns-adapter.html
Copyright © 2011-2022 走看看