概念
Bridge模式又叫做桥接模式,是构造型的设计模式之一,Bridge模式基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任,他的主要特点是保持各个部分的独立性以及对他们的拓展功能。
结构图
需求
现有发动机Engine4400c,Engine4500c,车BMW5 ,BMW5 ,通过桥接实现车和发动机的任意组合。
class Engine{
public:
virtual void engine() = 0;
virtual ~Engine(){}
};
class Car{
protected:
Engine *eng;
public:
virtual void installEngine() = 0;
virtual ~Car(){
delete eng;
}
};
class Engine4400c :public Engine{
public:
virtual void engine(){
cout << "Engine 4400c" << endl;
}
~Engine4400c(){
cout << "4400cdel" << endl;
}
};
class Engine4500c :public Engine{
public:
virtual void engine(){
cout << "Engine 4500c" << endl;
}
~Engine4500c(){
cout << "4500cdel" << endl;
}
};
class BMW5 :public Car{
public:
BMW5(Engine *eng){
this->eng = eng;
}
virtual void installEngine(){
cout << "BMW5" << endl;
eng->engine();
}
};
class BMW6 :public Car{
public:
BMW6(Engine *eng){
this->eng = eng;
}
virtual void installEngine(){
cout << "BMW6" << endl;
eng->engine();
}
};
int main(void){
BMW5 *b5 = new BMW5(new Engine4400c());
b5->installEngine();
BMW6 *b6 = new BMW6(new Engine4500c());
b6->installEngine();
delete b5;
delete b6;
system("pause");
return 0;
}
调试结果: