//Structural Patterns--Bridge
//结构型模式--桥接模式
//Abstraction(抽象类):用于定义抽象类的接口,并且维护一个指向 Implementor 实现类的指针。它与 Implementor 之间具有关联关系。
//RefinedAbstraction(扩充抽象类):扩充由 Abstraction 定义的接口,在 RefinedAbstraction 中可以调用在 Implementor 中定义的业务方法。
//Implementor(实现类接口):定义实现类的接口,这个接口不一定要与 Abstraction 的接口完全一致,事实上这两个接口可以完全不同。
//ConcreteImplementor(具体实现类):实现了 Implementor 定义的接口,在不同的 ConcreteImplementor 中提供基本操作的不同实现。
// 在程序运行时,ConcreteImplementor 对象将替换其父类对象,提供给 Abstraction 具体的业务操作方法。
//--------------------------------------------------------------
class IElectricalEquipment //电器,Implementor(实现类接口)
{
public:
virtual ~IElectricalEquipment(){}
virtual void PowerOn() = 0;
virtual void PowerOff() = 0;
};
class Light : public IElectricalEquipment //电灯,ConcreteImplementor(具体实现类)
{
public:
void PowerOn(){cout << "Light is on." << endl;}
void PowerOff(){cout << "Light is off." << endl;}
};
class Fan : public IElectricalEquipment //电扇,ConcreteImplementor(具体实现类)
{
public:
void PowerOn(){cout << "Fan is on." << endl;}
void PowerOff(){cout << "Fan is off." << endl;}
};
//--------------------------------------------------------------
class ISwitch //开关,Abstraction(抽象类)
{
public:
ISwitch(IElectricalEquipment *ee){m_pEe = ee;}
virtual ~ISwitch(){}
virtual void On() = 0;
virtual void Off() = 0;
protected:
IElectricalEquipment *m_pEe;
};
class PullChainSwitch : public ISwitch //拉链式开关,RefinedAbstraction(扩充抽象类)
{
public:
PullChainSwitch(IElectricalEquipment *ee):ISwitch(ee){}
void On(){cout<<"Switch on the equipment with a pull chain switch." << endl; m_pEe->PowerOn();}
void Off(){cout << "Switch off the equipment with a pull chain switch." << endl; m_pEe->PowerOn();}
};
class TwoPositionSwitch :public ISwitch //两位开关,RefinedAbstraction(扩充抽象类)
{
public:
TwoPositionSwitch(IElectricalEquipment *ee):ISwitch(ee){}
void On(){cout << "Switch on the equipment with a two-position switch." << endl; m_pEe->PowerOn();}
void Off(){cout << "Switch off the equipment with a two-position switch." << endl; m_pEe->PowerOff();}
};
//--------------------------------------------------------------
//测试
void dpBridgeTestMain()
{
//创建电灯,电扇
IElectricalEquipment *pLight = new Light();
IElectricalEquipment *pFan = new Fan();
//
ISwitch *pPullChain = new PullChainSwitch(pLight);
ISwitch *pTwoPosition = new TwoPositionSwitch(pFan);
pPullChain->On();
pPullChain->Off();
pTwoPosition->On();
pTwoPosition->Off();
if(pLight){delete pLight; pLight=NULL;}
if(pFan){delete pFan; pFan=NULL;}
if(pPullChain){delete pPullChain; pPullChain=NULL;}
if(pTwoPosition){delete pTwoPosition; pTwoPosition=NULL;}
return;
};