zoukankan      html  css  js  c++  java
  • 结构型设计模式之适配器模式(Adapter)

    结构


     

    意图 将一个类的接口转换成客户希望的另外一个接口。A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
    适用性
    • 你想使用一个已经存在的类,而它的接口不符合你的需求。
    • 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
    • (仅适用于对象A d a p t e r )你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。
     1  using System;
     2 
     3     class FrameworkXTarget 
     4     {
     5         virtual public void SomeRequest(int x)
     6         {
     7             // normal implementation of SomeRequest goes here                    
     8         }
     9     }
    10 
    11     class FrameworkYAdaptee
    12     {
    13         public void QuiteADifferentRequest(string str) 
    14         {
    15             Console.WriteLine("QuiteADifferentRequest = {0}", str);
    16         }        
    17     }
    18 
    19     class OurAdapter : FrameworkXTarget
    20     {
    21         private FrameworkYAdaptee adaptee = new FrameworkYAdaptee();
    22         override public void SomeRequest(int a)
    23         {
    24             string b;
    25             b = a.ToString();
    26             adaptee.QuiteADifferentRequest(b);
    27         }        
    28     }
    29 
    30     /// <summary>
    31     ///    Summary description for Client.
    32     /// </summary>
    33     public class Client
    34     {
    35         void GenericClientCode(FrameworkXTarget x)
    36         {
    37             // We assume this function contains client-side code that only 
    38             // knows about FrameworkXTarget.
    39             x.SomeRequest(4);
    40             // other calls to FrameworkX go here
    41             // ...
    42         }
    43         
    44         public static int Main(string[] args)
    45         {
    46             Client c = new Client();
    47             FrameworkXTarget x = new OurAdapter();
    48             c.GenericClientCode(x);    
    49             return 0;
    50         }
    51     }
    适配器模式
  • 相关阅读:
    Scrum Meeting Alpha
    Scrum Meeting Alpha
    Scrum Meeting Alpha
    你连自律都做不到,还奢谈什么自由?
    改变这个世界
    这世界没有人能随随便便成功
    “沙堆实验”
    解读那些年我们见过的“富人思维”
    心存希望,面朝大海
    闻香识女人 演讲台词
  • 原文地址:https://www.cnblogs.com/ziranquliu/p/4663310.html
Copyright © 2011-2022 走看看