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

Adapter 适配器模式

时间:2014-09-09 21:23:59      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   使用   ar   2014   

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

  • 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
  • 需要适配的类(Adaptee):需要适配的类或适配者类。
  • 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。  

有类适配器与对象适配器两种类型。

下列情况使用适配器模式:

  • 要使用的类的接口不符合需求。
  • 建立一个可复用的类,可以与不相关的类或不可预见的类协同工作。
  • 要使用一些已存在的子类,直接适配它的父类接口。


bubuko.com,布布扣

 1 #include <cstdio>
 2 
 3 class Adaptee {
 4 public:
 5     void SpecificRequest(int cost) {
 6         printf("such adaptee so %d\n", cost);
 7     }
 8 
 9 };
10 
11 class Target {
12 public:
13     virtual void Request() = 0;
14 };
15 
16 class AdapterCls : public Target, private Adaptee {
17 public:
18     void Request() {
19         SpecificRequest(100);
20     }
21 };
22 
23 class AdapterImp : public Target {
24 private:
25     Adaptee adaptee;
26 public:
27     void Request() {
28         adaptee.SpecificRequest(100);
29     }
30 };
31 
32 class Client
33 {
34 public:
35     Client();
36     ~Client();
37     void gaoCls() {
38         Target *p = new AdapterCls();
39         p->Request();
40         delete p;
41     }
42     void gaoImp() {
43         Target *p = new AdapterImp();
44         p->Request();
45         delete p;
46     }
47 private:
48 };
49 
50 Client::Client()
51 {
52 }
53 
54 Client::~Client()
55 {
56 }

 

Adapter 适配器模式

标签:style   blog   http   color   os   io   使用   ar   2014   

原文地址:http://www.cnblogs.com/zinthos/p/3963330.html

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