最近自学了设计模式,用C++自己实现的小例子,加深理解。
组合模式
定义:
将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用性:
1、 想要表示对象的部分-整体层次结构
2、 希望用户忽略组合对象与单个对象的不同,用户将统一的使用组合结构中的所有对象
优点:
1、 简化客户代码,客户可以一致的使用组合结构和单个对象
2、 容易添加新类型的组件
3、 设计变得更加一般化。
结构:
实现:
//书上写的add remove等操作参数类型都是对象,这里还是用指针的好,对象会出现截断。
class Component
{
public:
Component(){}
virtual~Component() //基类的析构函数,一定要virtual
{}
virtual void doSomething(){}
virtual void Add(Component *pChild){}
virtual void Remove(Component *pChild){}
virtualComponent* GetChild(int index)
{
returnNULL;
}
};
class Leaf:public Component
{
public:
Leaf(){}
~Leaf()
{
cout<<"delete Leaf"<<endl;
}
void doSomething()
{
cout<<"Leaf doSomething"<<endl;
}
};
class Composite:public Component
{
public:
Composite(){}
~Composite()
{
cout<<"delete Composite"<<endl;
}
voiddoSomething()
{
cout<<"CompositedoSomething"<<endl;
}
void Add(Component *pChild)
{
m_ChildVec.push_back(pChild);
}
void Remove(Component *pChild)
{
//用find算法比我们自己写for循环要好
vector<Component*>::iterator it =find(m_ChildVec.begin(),m_ChildVec.end(),pChild);
if (it !=m_ChildVec.end())
{
Component *temp = *it;
m_ChildVec.erase(it);
delete temp; //记得删除,免得内存泄漏
}
}
Component* GetChild(intindex)
{
if (index <m_ChildVec.size()) //记得判断索引是否合法
{
returnm_ChildVec[index];
}
return NULL;
}
private:
vector<Component*> m_ChildVec;
};
Leaf *pleaf1 = newLeaf;
Leaf *pleaf2 = newLeaf;
Leaf *pleaf3 = newLeaf;
Leaf *pleaf4 = newLeaf;
Composite *pbranch = new Composite;
Composite *pRoot = new Composite;
pRoot->Add(pleaf1);
pRoot->Add(pleaf2);
pbranch->Add(pleaf3);
pbranch->Add(pleaf4);
pRoot->Add(pbranch);
pbranch->doSomething();
pleaf1->doSomething();
Component * p = pbranch->GetChild(1);
pbranch->Remove(p);