在軟件系統中,某些類型由於自身的邏輯,它具有兩個或多個維度的變化,那麼如何應對這種“多維度的變化”?如何利用面嚮對象的技術來使得該類型能夠輕鬆的沿着多個方向進行變化,而又不引入額外的複雜度?這就要使用Bridge模式。
【GOF95】在提出橋樑模式的時候指出,橋樑模式的用意是"將抽象化(Abstraction)與實現化(Implementation)脫耦,使得二者可以獨立地變化"。這句話有三個關鍵詞,也就是抽象化、實現化和脫耦。
所謂耦合,就是兩個實體的行爲的某種強關聯。而將它們的強關聯去掉,就是耦合的解脫,或稱脫耦。在這裏,脫耦是指將抽象化和實現化之間的耦合解脫開,或者說是將它們之間的強關聯改換成弱關聯。
將兩個角色之間的繼承關係改爲聚合關係,就是將它們之間的強關聯改換成爲弱關聯。因此,橋樑模式中的所謂脫耦,就是指在一個軟件系統的抽象化和實現化之間使用組合/聚合關係而不是繼承關係,從而使兩者可以相對獨立地變化。這就是橋樑模式的用意。
1、Bridge.h
#ifndef _BRIDGE_H_
#define _BRIDGE_H_
#include <iostream>
using namespace std;
class TeacherImpl
{
public :
virtual void teachStart()=0;
virtual void teachStop()=0;
};
class Teacher
{
protected :
TeacherImpl * tech;
public :
Teacher(TeacherImpl * tech)
{
this->tech=tech;
}
void start()
{
tech->teachStart();
}
void stop()
{
tech->teachStop();
}
void display()
{
start();
stop();
}
};
class ChinaTeacher:public Teacher
{
public :
ChinaTeacher(TeacherImpl * tech ):Teacher(tech){}
void display1()
{
for(int i=0;i<4;i++)
{
start();
stop();
}
}
};
class TeacherManager:public TeacherImpl
{
public :
virtual void teachStart()
{
cout<<"teachStart"<<endl;
}
virtual void teachStop()
{
cout<<"teachStop"<<endl;
}
};
#endif
2、Client.cpp
#include <iostream>
#include <string>
#include "Bridge.h"
using namespace std;
int main()
{
TeacherImpl * impl=new TeacherManager();
Teacher * teacher=new Teacher(impl);
teacher->display();
ChinaTeacher * china=new ChinaTeacher(impl);
china->display1();
system("pause");
return 0;
}