实验8:适配器模式
[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
直接放源码:
#include<iostream> #include<string> using namespace std; class CatTarget { public: virtual void catchMouse() = 0; }; class ConcreteCatTarget:public CatTarget { public: void catchMouse() { cout<<"抓老鼠"<<endl; } }; class DogAdaptee { public: virtual void wang()=0; }; class ConcreteDogAdaptee:public DogAdaptee { public: void wang() { cout<<"汪汪叫"<<endl; } }; class Adapter:public CatTarget,public DogAdaptee { private: CatTarget *catTarget; DogAdaptee *dogAdaptee; public: Adapter() { } void setCatTarget(CatTarget *catTarget) { this->catTarget = catTarget; } void setDogAdaptee(DogAdaptee *dogAdaptee) { this->dogAdaptee = dogAdaptee; } void catchMouse() { cout<<"猫学狗叫,即目标类调用适配者中的方法:"<<endl; dogAdaptee->wang(); } void wang(){ cout<<"狗学猫抓老鼠,即适配者调用目标类中的方法:"<<endl; catTarget->catchMouse(); } }; int main() { //适配器 Adapter *adapter=new Adapter(); adapter->setCatTarget(new ConcreteCatTarget()); adapter->wang(); adapter->setDogAdaptee(new ConcreteDogAdaptee()); adapter->catchMouse(); }
标签:软件设计,void,public,实验,new,adapter,catchMouse,适配器 From: https://www.cnblogs.com/lyf3701/p/16787046.html