res:http://hi.baidu.com/xuehuo_0411/item/1a026712246d9322f6625cd4
// BridgePattern.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
设计模式 桥接模式 C++实现
桥接模式(Bridge)分离了类的抽象和实现,使它们可以彼此独立地变化而互不影响。桥接模式与适配器模式有些相似,在两个对象之间加入了一个中间层次,提供间接联系增加了系统的灵活性。但两者的意图不同,适配器模式关心的是接口不匹配的问题,不关心接口的实现,只要求对象能够协同工作。桥接模式的侧重点是接口和实现,通常接口是稳定的,桥接解决实现的变化问题。
GOOD:将抽象部分与实现部分分离,使它们可以独立变化。
这里说的意思不是让抽象基类与具体类分离,而是现实系统可能有多角度分类,每一种分类都有可能变化,那么把这种多角度分离出来让它们独立变化,减少它们之间的耦合性,即如果继承不能实现“开放-封闭原则”的话,就应该考虑用桥接模式。
C++实现:
#include <iostream>
using namespace std;
//手机软件基类
class CellphoneSoft
{
public:
virtual void Run() = 0;
};
//手机游戏软件类,具体的软件类,继承于手机软类
class CellphoneGame : public CellphoneSoft
{
public:
virtual void Run() { cout << "run the mobile game" << endl; }
};
//手机号码簿类
class CellphoneAddressList : public CellphoneSoft
{
public:
virtual void Run() { cout << "run the cellphone's address book" << endl; }
};
//手机品牌类
class CellphoneBrand
{
public:
void SetCellphoneSoft(CellphoneSoft* tempSoft) { m_soft = tempSoft; }
virtual void Run() = 0;
protected:
CellphoneSoft* m_soft;
};
//M品牌
class CellphoneBrandM : public CellphoneBrand
{
public:
virtual void Run() { m_soft->Run(); }
};
//N品牌
class CellphoneBrandN : public CellphoneBrand
{
public:
virtual void Run() { m_soft->Run(); }
};
int main()
{
CellphoneBrand* brandM = new CellphoneBrandM();
brandM->SetCellphoneSoft(new CellphoneGame());
brandM->Run();
CellphoneBrand* brandN = new CellphoneBrandN();
brandN->SetCellphoneSoft(new CellphoneAddressList());
brandN->Run();
return 0;
}