#include <iostream>#include <list>using namespace std;// 抽象介面class CUSBDevice{public: virtual ~CUSBDevice(){} virtual void Add(CUSBDevice* _pDev){} virtual void Remove(CUSBDevice* _pDev){} virtual void Transmit(){} virtual int GetChild(){return 0;}};// 單一個對象,不能添加新組件class CUSBMouse : public CUSBDevice{public: virtual void Transmit() { cout<<"傳遞滑鼠移動點擊資訊"<<endl; }};// 組合對象,可以添加多個新組件class CUSBHub : public CUSBDevice{public: virtual void Add(CUSBDevice* _pDev) { m_listDev.push_back(_pDev); } virtual void Remove(CUSBDevice* _pDev) { m_listDev.remove(_pDev); } virtual void Transmit() { cout<<"傳輸USBHub資訊"<<endl; } virtual int GetChild() { return m_listDev.size(); }private: list<CUSBDevice*> m_listDev;};
// 電腦主機先接了一個HubA,HubA再接了一個USB滑鼠以及又一個USBHubB
// USBHubB又接一個USB滑鼠
int _tmain(int argc, _TCHAR* argv[]){ // 先建立一個USBHub CUSBHub hubA; CUSBDevice* pUSBMA = new CUSBMouse; hubA.Add(pUSBMA); // USBHubB CUSBDevice* pUSBHubB = new CUSBHub; CUSBDevice* pUSBMB = new CUSBMouse; pUSBHubB->Add(pUSBMB); hubA.Add(pUSBHubB); // 移除裝置 if (pUSBMA->GetChild() > 0) { cout<<"移除裝置"<<endl; } delete pUSBMA; delete pUSBMB; delete pUSBHubB; return 0;}
注意:抽象基類的解構函式一定要是虛函數,否則記憶體釋放的時候會有問題。
優缺點:
參考資料: