设计模式适配器模式
题目
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
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; } TwoElectricAdapter::TwoElectricAdapter(ThreeElectricOutlet *outlet) { myOutlet = outlet; } void TwoElectricAdapter::connectElectricCurrent() { myOutlet->connectElectricCurrent(); 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; } main() { ThreeElectricOutlet *outlet; TwoElectricOutlet *two; Wash *wash = new Wash(); TwoElectricAdapter *te = new TwoElectricAdapter(wash); two = te; two->connectElectricCurrent(); Tv *tv = new Tv(); ThreeElectricAdapter *adapter = new ThreeElectricAdapter(tv); outlet = adapter; outlet->connectElectricCurrent(); }