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

    双向适配器:

     

     

    示例代码:

  • 相关阅读:
    第3章 机器学习的典型应用 3-2 典型应用-聚类
    第3章 机器学习的典型应用 3-1 典型应用-关联规则
    6-13 Hog特征1
    6-12 SVM小结
    Linux中常见的环境变量笔记
    Linux中常见的环境变量笔记
    Linux中shell变量基础概念笔记
    Linux中shell变量基础概念笔记
    Linux常用内建命令笔记
    Linux常用内建命令笔记
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3993334.html
Copyright © 2011-2022 走看看