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

    结构型设计模式大比拼

      共同点 不同点
    装饰者模式 对象包装 不改变接口,加入新的职责
    适配器模式   不改变职责,改变接口
    外观模式   简化高层接口,统一调用
  • 相关阅读:
    spring子模块----->Spring Security------->相关教程(参考资料)
    Maven--->学习心得--->maven 概述
    Spring和Spring MVC 、Spring Security的关系
    leapMotion简介
    软件工程需求分析
    大型web网站-----系统架构
    Maven的安装与配置
    A Java Exception occured 解决
    mysql-5.7.20安装和配置
    线段树 poj 3667
  • 原文地址:https://www.cnblogs.com/fecktty2013/p/designpatterns-adapter.html
Copyright © 2011-2022 走看看