適配器模式及C++實現


適配器模式

適配器模式是很好理解的模式了,生活中也非常常見,什么插頭2口轉3口,什么USB轉PS2,這都算是適配器模式。說白了,就是如果有一些東西提供的接口你很像用,但是你手頭沒有好的接口使用它,這個就需要一個適配器,將你需要的接口轉換成你所擁有的接口。這樣的好處也是顯而易見,就是你不用改變你現在所擁有的接口,保證你在任何地方的用法都不需要修改,然后底層的實現由適配器調用需要的接口來具體實現。

image

 

常見的場景

使用第三方庫的時候,第三方的庫肯定不能適用所有的系統,所以需要一個適配器來轉換。

 

優點

1.屏蔽了具體的實現方式,實現了依賴倒轉。

2.可以把不統一的接口封裝起來,使之成為統一的接口。

3.把本來不方便適用的接口轉換成統一的接口。

 

缺點

 

C++實現

 

 1 #ifndef _ADAPTER_H_
 2 #define _ADAPTER_H_
 3 
 4 #include "Adaptee.h"
 5 
 6 
 7 class Target
 8 {
 9 public:
10     Target();
11     virtual ~Target();
12 
13     virtual void request() = 0;
14 };
15 
16 
17 class Adapter: public Target
18 {
19 public:
20     Adapter();
21     ~Adapter();
22 
23     void request();
24 
25 
26 private:
27     Adaptee* adaptee;
28 };
29 
30 
31 #endif
 1 #include "Adapter.h"
 2 
 3 
 4 Target::Target()
 5 {
 6 
 7 }
 8 
 9 
10 Target::~Target()
11 {
12 
13 }
14 
15 
16 Adapter::Adapter():
17     adaptee(new Adaptee())
18 {
19 
20 }
21 
22 
23 Adapter::~Adapter()
24 {
25 
26 }
27 
28 
29 void Adapter::request()
30 {
31     adaptee->specificRequest();
32 }
 1 #ifndef _ADAPTEE_H_
 2 #define _ADAPTEE_H_
 3 
 4 class Adaptee
 5 {
 6 public:
 7     Adaptee();
 8     ~Adaptee();
 9 
10     void specificRequest();
11 
12 };
13 
14 
15 #endif
 1 #include "Adaptee.h"
 2 #include <stdio.h>
 3 
 4 
 5 Adaptee::Adaptee()
 6 {
 7 
 8 }
 9 
10 
11 Adaptee::~Adaptee()
12 {
13 
14 }
15 
16 
17 void Adaptee::specificRequest()
18 {
19     fprintf(stderr, "this is specificRequest\n");
20 }
1 #include "Adapter.h"
2 
3 
4 int main()
5 {
6     Target* tar = new Adapter();
7     tar->request();
8     return 0;
9 }
1 g++ -o client client.cpp Adapter.cpp Adaptee.cpp

 

運行結果

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM