桥接模式:将抽象与实现解耦,使得两者可以独立地变化,抽象部分的对象去使用具体实现部分的对象
#include <iostream>
using namespace std;
class CommunicateTool
{
public:
CommunicateTool(){}
virtual ~CommunicateTool(){}
virtual void communicate(const char* msg){
cout << msg << endl;
}
};
class Phone:public CommunicateTool{
public:
void communicate(const char *msg){
cout << msg << "(使用电话)" << endl;
}
};
class Email:public CommunicateTool{
public:
void communicate(const char* msg){
cout << msg << "(使用电子邮件)" << endl;
}
};
class People
{
public:
People(){
mTool = new CommunicateTool;
}
~People()
{
delete mTool;
mTool = NULL;
}
void setCommunicateTool(CommunicateTool* tool){
mTool = tool;
}
virtual void communicate(const char* msg){
mTool->communicate(msg);
}
private:
CommunicateTool *mTool;
};
class Chinese:public People
{
public:
void communicate(const char* msg)
{
cout << "使用中文:";
People::communicate(msg);
}
};
class English:public People
{
public:
void communicate(const char* msg)
{
cout << "use English:";
People::communicate(msg);
}
};
int main()
{
People* chinese = new Chinese;
chinese->communicate("你好");
chinese->setCommunicateTool(new Phone);
chinese->communicate("你好,世界");
People* english = new English;
english->communicate("hello");
english->setCommunicateTool(new Email);
english->communicate("hello,world");
}
使用中文:你好
使用中文:你好,世界(使用电话)
use English:hello
use English:hello,world(使用电子邮件)