標籤: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——適配器模式