每日博客
适配器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解适配器模式的动机,掌握该模式的结构;
2、能够利用适配器模式解决实际问题。
[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
#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();
}