适配器模式-c++
#include <iostream> #include <string> using namespace std; class ThreeElectricOutlet { public: virtual void connectElectricCurrent() = 0; }; class TwoElectricOutlet { public: virtual void connectElectricCurrent() = 0; }; class ThreeElectricAdapter : public ThreeElectricOutlet { private: TwoElectricOutlet *myOutlet; public: ThreeElectricAdapter(TwoElectricOutlet *outlet); void connectElectricCurrent(); }; class TwoElectricAdapter : public TwoElectricOutlet { private: ThreeElectricOutlet *myOutlet; public: TwoElectricAdapter(ThreeElectricOutlet *outlet); void connectElectricCurrent(); }; class Wash : public ThreeElectricOutlet { public: Wash(); Wash(string s); void connectElectricCurrent(); private: string name; }; class Tv : public TwoElectricOutlet { public: Tv(); Tv(string s); void connectElectricCurrent(); private: string name; }; ThreeElectricAdapter::ThreeElectricAdapter(TwoElectricOutlet *outlet) { myOutlet = outlet; } void ThreeElectricAdapter::connectElectricCurrent() { myOutlet->connectElectricCurrent(); cout << "模仿" << endl; cout << "抓老鼠" << endl; } TwoElectricAdapter::TwoElectricAdapter(ThreeElectricOutlet *outlet) { myOutlet = outlet; } void TwoElectricAdapter::connectElectricCurrent() { myOutlet->connectElectricCurrent(); cout << "模仿" << endl; cout << "汪汪叫" << endl; } Wash::Wash() { name = "猫"; } Wash::Wash(string s) { name = s; } void Wash::connectElectricCurrent() { cout << name << endl; } Tv::Tv() { name = "狗"; } Tv::Tv(string s) { name = s; } void Tv::connectElectricCurrent() { cout << name << endl; } int main() { ThreeElectricOutlet *outlet; TwoElectricOutlet *two; Wash *wash = new Wash(); TwoElectricAdapter *te = new TwoElectricAdapter(wash); two = te; two->connectElectricCurrent(); cout << "***************" << endl; Tv *tv = new Tv(); ThreeElectricAdapter *adapter = new ThreeElectricAdapter(tv); outlet = adapter; outlet->connectElectricCurrent(); }