组合模式是结构型模式的一种,通过添加删除组件,遍历去执行操作。
#ifndef __COMPOSITE_H__ #define __COMPOSITE_H__ #include using namespace std; class IElement { protected: IElement() {} public: virtual ~IElement() {} public: virtual void Test() = 0; }; class CElementA : public IElement { public: CElementA() {} ~CElementA() {} public: void Test() {printf("CElementA::Test()\n");} }; class CElementB : public IElement { public: CElementB() {} ~CElementB() {} public: void Test() {printf("CElementB::Test()\n");} }; class CComposite { public: CComposite(); ~CComposite(); public: void Add(IElement* pElem); void Remove(IElement* pElem); void RemoveAll(); IElement* GetChild(int nIndex); public: void Test(); private: vector m_vecElem; // 如用于多线程中请自行加锁 }; #endif // __COMPOSITE_H__#include "stdafx.h" #include "Composite.h" CComposite::CComposite() { } CComposite::~CComposite() { RemoveAll(); } void CComposite::Add(IElement* pElem) { m_vecElem.push_back(pElem); } void CComposite::Remove(IElement* pElem) { vector ::iterator iter = m_vecElem.begin(); while (iter != m_vecElem.end()) { if (*iter == pElem) { delete pElem; m_vecElem.erase(iter); return; } iter++; } } void CComposite::RemoveAll() { for (unsigned int i = 0; i < m_vecElem.size(); i++) { delete m_vecElem[i]; } m_vecElem.clear(); } IElement* CComposite::GetChild(int nIndex) { return m_vecElem[nIndex]; } void CComposite::Test() { for (unsigned int i = 0; i < m_vecElem.size(); i++) { m_vecElem[i]->Test(); } } #include "stdafx.h" #include "Composite.h" int _tmain(int argc, _TCHAR* argv[]) { CComposite com; com.Add(new CElementA); com.Add(new CElementB); com.Test(); getchar(); com.RemoveAll(); com.Test(); getchar(); return 0; } ithewei 认证博客专家 c/c Qt libhv 编程之路,其路漫漫,吾将上下而求索https://github.com/itheweihttps://hewei.blog.csdn.net