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等面向对象编程语言中,大部分情况下我们使用的是对象适配器,类适配器较少使用

    双向适配器:

     

     

    示例代码:

  • 相关阅读:
    Application Error
    war文件
    The connection to adb is down, and a severe error has occured.
    CORS解决跨域访问问题
    实验吧_拐弯抹角(url伪静态)&Forms
    系列文章(一):探究电信诈骗的关键问题与应对策略——By Me
    企业内部安全宣贯:乌云网停摆事件的思考与评论——By Me
    安全需求-建模归类——By Me
    思考在伟大的互联网世界中,我是谁?——By Me in 2016
    去把bilibili的返回顶点锚点扒了下来
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3993334.html
Copyright © 2011-2022 走看看