桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。
例如现在的手机硬件与软件,电脑硬件和软件,都是通过不同的厂商来开发的。它们之间都不是谁依赖谁的关系,都是往中间抽象层依靠。
手机与软件实现:
//合成/聚合复用原则:尽量使用合成/聚合,尽量不要使用类继承
#include <iostream>
using namespace std;
class HandsetSoft
{
public:
virtual void Run() = 0;
};
//手机游戏
class HandsetGame : public HandsetSoft
{
public:
void Run()
{
cout << "运行手机游戏" << endl;
}
};
//手机通讯录
class HandsetAddressList : public HandsetSoft
{
public:
void Run()
{
cout << "运行手机通讯录" << endl;
}
};
//手机品牌
class HandsetBrand
{
public:
void SetHandsetSoft(HandsetSoft* soft)
{
this->soft = soft;
}
virtual void Run()= 0;
protected:
HandsetSoft* soft;
};
class HandsetBrandN : public HandsetBrand
{
public:
void Run()
{
soft->Run();
}
};
class HandsetBrandM : public HandsetBrand
{
public:
void Run()
{
soft->Run();
}
};
int main()
{
HandsetBrand* ab = new HandsetBrandN();
ab->SetHandsetSoft(new HandsetGame());
ab->Run();
ab->SetHandsetSoft(new HandsetAddressList());
ab->Run();
ab = new HandsetBrandM();
ab->SetHandsetSoft(new HandsetGame());
ab->Run();
ab->SetHandsetSoft(new HandsetAddressList());
ab->Run();
}
电脑与系统的实现:
//操作系统--电脑
#include <iostream>
using namespace std;
class OS
{
public:
virtual void OS_operation() = 0;
};
class Windows : public OS
{
void OS_operation()
{
cout << "Windows" << endl;
}
};
class Linux : public OS
{
void OS_operation()
{
cout << "Linux" << endl;
}
};
class Unix : public OS
{
void OS_operation()
{
cout << "Unix" << endl;
}
};
class Computer
{
public:
virtual void InstallOS(OS* os) = 0;
};
class HuaweiComputer : public Computer
{
void InstallOS(OS* os)
{
os->OS_operation();
}
};
class AppleComputer : public Computer
{
void InstallOS(OS* os)
{
os->OS_operation();
}
};
class QilinComputer : public Computer
{
void InstallOS(OS* os)
{
os->OS_operation();
}
};
int main()
{
OS* os1 = new Windows();
OS* os2 = new Linux();
OS* os3 = new Unix();
Computer* computer1 = new HuaweiComputer();
Computer* computer2 = new AppleComputer();
Computer* computer3 = new QilinComputer();
computer1->InstallOS(os1);
computer2->InstallOS(os3);
computer3->InstallOS(os2);
return 0;
}