1. 程式人生 > >設計模式--結構型模式--橋接模式

設計模式--結構型模式--橋接模式

//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; };