桥接模式其实是合成/聚合规则的一种体现,尽量使用合成/聚合规则,不要使用类继承。聚合表示一种弱的拥有关系,体现的是A对象可以包含B对象,但B对象不是A对象的一部分,合成则是一种强的拥有关系,体现了严格的部分和整体的关系,部分和整体的生命周期是一样的。
代码如下:
#ifndef __HANDSET__BRAND__H__
#define __HANDSET__BRAND__H__
#include "HandsetSoft.h"
class HandsetBrand
{
public:
HandsetBrand() {}
virtual ~HandsetBrand() {}
virtual void Run() {}
void SetHandlesetSoft( HandsetSoft* hss)
{
m_pSoft = hss;
}
protected:
HandsetSoft *m_pSoft;
};
class HandsetBrandM :public HandsetBrand
{
public:
HandsetBrandM() {}
~HandsetBrandM() {}
virtual void Run()
{
m_pSoft->Run();
}
};
class HandsetBrandN:public HandsetBrand
{
public:
HandsetBrandN() {}
~HandsetBrandN() {}
virtual void Run()
{
m_pSoft->Run();
}
};
#endif // !__HANDSET__BRAND__H__
#ifndef __HANDSET__SOFT__H__
#define __HANDSET__SOFT__H__
#include <iostream>
using std::cout;
using std::endl;
class HandsetSoft
{
public:
HandsetSoft() {}
virtual ~HandsetSoft() {}
virtual void Run() {}
};
class HandsetGame :public HandsetSoft
{
public :
HandsetGame() {}
~HandsetGame() {}
virtual void Run()
{
cout << "Run handset game" << endl ;
}
};
class HandsetAddressList :public HandsetSoft
{
public:
HandsetAddressList() {}
~HandsetAddressList() {}
virtual void Run()
{
cout << "Run handset address list" << endl;
}
};
#endif // !__HANDSET__SOFT__H__
int _tmain(int argc, TCHAR* argv[])
{
HandsetBrand * hb = new HandsetBrandM();
HandsetSoft * hs = new HandsetGame();
hb->SetHandlesetSoft(hs);
hb->Run();
if (hs)
{
delete hs;
hs = NULL;
}
hs = new HandsetAddressList();
hb->SetHandlesetSoft(hs);
hb->Run();
if (hs)
{
delete hs;
hs = NULL;
}
if (hb)
{
delete hb;
hb = NULL;
}
}
结果如下所示: