您的位置:首页 > 其它

设计模式-桥接模式

2016-07-19 19:06 351 查看
桥接模式Bridge):

    将抽象部分与它的实现部分分离,使他们都可以独立地变化。



    需要解释一下,什么叫做抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。也就是说手机既可以按照品牌分类又可以按照功能分类。





    由于实现的方式有多种,桥接模式的核心意图就是把这些实现独立出来,让他们各自的变化,这就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。



桥接模式代码:

#pragma once
#include <string>
#include <iostream>
using namespace std;

//implementor
class CImplementor
{
public:
virtual void Operation() = 0;
};

//ConcreteImplementorA,ConcreteImplementorB
class CConcreteImplementorA : public CImplementor
{
public:
void Operation()
{
cout<<"Execution method A"<<endl;
}
};
class CConcreteImplementorB : public CImplementor
{
public:
void Operation()
{
cout<<"Execution method B"<<endl;
}
};

//Abstraction
class CAbstraction
{
protected:
CImplementor *m_pImplementor;
public:
CAbstraction(){m_pImplementor = NULL;}
void SetImplementor(CImplementor *pImplementor)
{
m_pImplementor = pImplementor;
}
virtual void Operation() = 0;
};

//RefinedAbstraction
class CRefinedAbstraction : public CAbstraction
{
public:
void Operation()
{
if(m_pImplementor != NULL)
{
m_pImplementor->Operation();
}
}
};客户端调用代码:
#include "stdafx.h"
#include "BridgeMode.h"
using namespace std;

int main()
{
CAbstraction *pAb = new CRefinedAbstraction();
CConcreteImplementorA *pcA = new CConcreteImplementorA();
CConcreteImplementorB *pcB = new CConcreteImplementorB();
pAb->SetImplementor(pcA);
pAb->Operation();
pAb->SetImplementor(pcB);
pAb->Operation();

delete pAb;
delete pcA;
delete pcB;
return 0;
}
执行结果:



总结:

    实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息