意图:
将抽象部分与它的实现部分分离,使它们都可以独立的变化
适用性:
1不希望在抽象和它的实现部分之间有一个固定的绑定关系
2类的抽象以及它的实现方法都应该可以通过生成子类的方法加以扩充
3对一个抽象的实现部分的修改应对客户不产生影响
4对客户完全隐藏抽象的实现部分
效果:
1分离接口及其实现部分 一个实现未必不变地绑定在一个接口上,抽象类的实现可以在运行时刻进行配置
2提高可扩充性 可独立的对Abstraction和Implementation层次结构进行扩充
3实现细节对客户透明
实现:
1仅有一个Implementor 没有必要创建一个抽象的Implementor类
2创建正确的Implementor对象
3共享Implementor对象
4采用多重继承机制,可以将抽象接口和它的实现部分结合起来
其示例代码如下:
Bridge.h
- #include <iostream>
- using namespace std;
- class WindowImp
- {
- public:
- virtual void DeviceRect(int,int,int,int)=0;
- WindowImp(){cout<<"XWindowImp is called"<<endl;}
- };
- class Window
- {
- public:
- Window();
- virtual void DrawContents();
- virtual WindowImp* GetWindowImp(int i);
- //private:
- WindowImp* _imp;
- };
- class ApplicationWindow: public Window
- {
- public:
- virtual void DrawContents();
- };
- class XWindowImp:public WindowImp
- {
- public:
- XWindowImp(){cout<<"XWindowImp is called"<<endl;}
- virtual void DeviceRect(int,int,int,int)
- {cout<<"Draw DeviceRect on XWindowImp"<<endl;}
- };
- class PMWindowImp:public WindowImp
- {
- public:
- PMWindowImp(){cout<<"PMWindowImp is called"<<endl;}
- virtual void DeviceRect(int,int,int,int)
- {
- cout<<"Draw DeviceRect on PMWindowImp"<<endl;
- }
- };
- class WindowSystemFactory
- {
- public:
- static WindowSystemFactory* Instance();
- WindowImp* MakeWindowImp(int i);
- WindowSystemFactory();
- private:
- static WindowSystemFactory* _instance;
- };
Bridge.cpp
- #include "Bridge.h"
- #include <iostream>
- using namespace std;
- Window::Window()
- {cout<<"A window is created."<<endl;
- _imp = 0;
- }
- void Window::DrawContents()
- {cout<<"Draw contents on the window"<<endl;}
- void ApplicationWindow::DrawContents()
- {cout<<"Draw contents on the application window"<<endl;}
- WindowImp* Window::GetWindowImp(int i)
- {
- if(_imp == 0)
- {
- //_imp = WindowSystemFactory::Instance()->MakeWindowImp(i);
- _imp = new XWindowImp();
- }
- cout<<"IMP is returned"<<endl;
- //_imp->DeviceRect(1,2,3,4);
- return _imp;
- /* _imp = new XWindowImp();
- return _imp;
- */
- }
- WindowSystemFactory::WindowSystemFactory()
- {
- cout<<"A WindowSystemFactory is created"<<endl;
- }
- WindowSystemFactory* WindowSystemFactory::_instance =0;
- WindowSystemFactory* WindowSystemFactory::Instance()
- {
- //cout<<"Enter an instance."<<endl;
- if(_instance == 0)
- {
- _instance = new WindowSystemFactory();
- cout<<"An instance is created successfully."<<endl;
- }
- else
- cout<<"An instance is already existed."<<endl;
- return _instance;
- }
- WindowImp* WindowSystemFactory::MakeWindowImp(int i)
- {
- switch (i)
- {
- case 0:
- return new XWindowImp;
- case 1:
- return new PMWindowImp;
- default:
- return new PMWindowImp;
- }
- }
main.cpp
- #include "Bridge.h"
- #include <iostream>
- using namespace std;
- int main()
- {
- ApplicationWindow a;
- WindowImp* c;
- WindowImp* d;
- d = new XWindowImp;
- d->DeviceRect(1,2,3,4);
- c=a.GetWindowImp(1);
- c->DeviceRect(1,2,3,4);
- return 0;
- }