实验8:适配器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解适配器模式的动机,掌握该模式的结构;
2、能够利用适配器模式解决实际问题。
[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
#include <iostream>
#include <string>
using namespace std;
class Cat
{
public:
virtual void catlook(){}
virtual void catchM(){}
};
class CatImpl:public Cat
{
public:
void catlook()
{
cout<<"猫的样子"<<endl;
}
void catchM()
{
cout<<"猫抓老鼠"<<endl;
}
};
class Dog
{
public:
virtual void doglook(){}
virtual void wang(){}
};
class DogImpl:public Dog
{
public:
void doglook()
{
cout<<"狗的样子"<<endl;
}
void wang()
{
cout<<"狗汪汪叫"<<endl;
}
};
class Adapter : public Cat,Dog
{
private:
Dog *DogImpl;
Cat *CatImpl;
public:
Adapter(Dog *DogImp,Cat *CatImp)
{
DogImpl=DogImp;
CatImpl=CatImp;
}
virtual void doglook()
{
cout<<"狗模仿";
CatImpl->catlook();
}
virtual void wang()
{
cout<<"狗模仿";
CatImpl->catchM();
}
virtual void catlook()
{
cout<<"猫模仿";
DogImpl->doglook();
}
virtual void catchM()
{
cout<<"猫模仿";
DogImpl->wang();
}
};
int main()
{
DogImpl *DogImp=new DogImpl();
CatImpl *CatImp=new CatImpl();
Adapter *adapter = new Adapter(DogImp,CatImp);
adapter->catlook();
adapter->catchM();
cout<<"**************"<<endl;
adapter->doglook();
adapter->wang();
return 0;
}