码迷,mamicode.com
首页 > 其他好文 > 详细

结构型设计模式之适配器模式

时间:2015-07-21 09:00:08      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

结构


 技术分享

技术分享

意图 将一个类的接口转换成客户希望的另外一个接口。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     }
适配器模式

 

结构型设计模式之适配器模式

标签:

原文地址:http://www.cnblogs.com/ziranquliu/p/4663310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!