設計模式14——適配器模式

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   2014   div   

適配器模式可以使介面不相同的幾個對象通過適配來統一介面。Target與Adaptee各自擁有自己的方法,但介面不同,可以通過Adapter進行統一。

 1 #ifndef Adapter_H_H 2 #define Adapter_H_H 3  4 #include <iostream> 5 using namespace std; 6  7 class Target 8 { 9 public:10     virtual void display() { cout << "This is a common target!" << endl; }11     virtual ~Target() {}12 };13 14 class Adaptee15 {16 public:17     void specialDisplay() { cout << "This is a special target!" << endl; }18 };19 20 class Adapter : public Target21 {22 public:23     Adapter() : adaptee(new Adaptee()) {}24     virtual void display() { adaptee->specialDisplay(); }25     ~Adapter() { delete adaptee; }26 27 private:28     Adaptee *adaptee;29 };30 31 32 void AdapterTest()33 {34     Target *target1 = new Target();35     Target *target2 = new Adapter();36 37     target1->display();38     target2->display();39 40     delete target1;41     delete target2;42 }43 44 45 #endif

運行結果:

Adaptee與Target介面不同,卻可以通過Adapter進行統一。

設計模式14——適配器模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.