zoukankan      html  css  js  c++  java
  • CSharp设计模式读书笔记(7):适配器模式(学习难度:★★☆☆☆,使用频率:★★★★☆)

    适配器模式(Adapter Pattern):将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。

    模式角色与结构:

    对象适配器:

    示例代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CSharp.DesignPattern.AdapterPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Adaptee adaptee = new Adaptee();
                Target target = new Adapter(adaptee);
                target.Request();
    
                Console.ReadLine();
            }
        }
    
        class Adapter : Target
        {
            private Adaptee adaptee;
    
            public Adapter(Adaptee adaptee)
            {
                this.adaptee = adaptee;
            }
    
            public void Request()
            {
                adaptee.Operation();
            }
        }
    
        interface Target
        {
            void Request();
        }
    
        class Adaptee
        {
            public void Operation()
            { }
        }
    }

    类适配器:

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CSharp.DesignPattern.AdapterPattern
    {
        class Program
        {
            static void Main(string[] args)
            {
                Target target = new Adapter();
                target.Request();
    
                Console.ReadLine();
            }
        }
    
        class Adapter : Adaptee, Target
        {
            public void Request()
            {
                this.Operation();
            }
        }
    
        interface Target
        {
            void Request();
        }
    
        class Adaptee
        {
            public void Operation()
            { }
        }
    }

    由于Java、C#等语言不支持多重类继承,因此类适配器的使用受到很多限制,例如如果目标抽象类Target不是接口,而是一个类,就无法使用类适配器;此外,如果适配者Adapter为最终(Final)类,也无法使用类适配器。在Java等面向对象编程语言中,大部分情况下我们使用的是对象适配器,类适配器较少使用

    双向适配器:

     

     

    示例代码:

  • 相关阅读:
    喜马拉雅第三方客户端开发(接口和接口数据解析)。
    jquery-easyui中datagrid扩展,隐藏显示表头功能
    backbone ,jQuery-easyui,knockoutjs的整合使用
    WPF中的瀑布流布局(TilePanel)控件
    使用this.$refs['formName'].resetFields()无法重置表单
    js获取json对象的key值
    Hash表算法详解
    Redis入门
    ASP.Net 下载大文件的实现
    后端生成二维码
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3993334.html
Copyright © 2011-2022 走看看