適配器模式及C++實現

來源:互聯網
上載者:User
適配器模式

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

 

常見的情境

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

 

優點

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 Target18 {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

 

運行結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.