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     }
    适配器模式
  • 相关阅读:
    ●BZOJ 3926 [Zjoi2015]诸神眷顾的幻想乡
    ●BZOJ 1396 识别子串
    ●UVA 1608 Non-boring sequences
    ●SPOJ 8222 NSUBSTR–Substrings
    ●SPOJ 7258 Lexicographical Substring Search
    ●CodeForces 429D Trick_Function
    ●BZOJ 2555 SubString
    ●洛谷P2664 树上游戏
    ●洛谷P3168 [CQOI2015]任务查询系统
    【UVA1057】Routing
  • 原文地址:https://www.cnblogs.com/ziranquliu/p/4663310.html
Copyright © 2011-2022 走看看