组合模式(Composite)定义
将对象组合成树形结构以表示"部分-整体"的层次结构,Composite使得用户对单个对象和组合对象的使用具有一致性(稳定)。
组合模式结构图
示例代码
class Component
{
public:
virtual void OnShow() = 0;
virtual ~Component() {}
};
//树节点
class Composite : public Component
{
private:
std::string strName;
std::list<Component*> m_lstElements; //树型结构
public:
Composite(const std::string& sName) : strName(sName){
}
void Add(Component* element)
{
m_lstElements.push_back(element);
}
void Remove(Component* element)
{
m_lstElements.remove(element);
}
void OnShow()
{
cout << "Composite name: " << strName.c_str() << endl;
for (auto &c : m_lstElements)
{
c->OnShow();
}
}
};
//叶子节点
class Leaf : public Component
{
private:
std::string strName;
public:
Leaf(const std::string& sName) : strName(sName){
}
void OnShow()
{
cout << "Leaf name: " << strName.c_str() << endl;
}
};
void Invoke(Component& c)
{
c.OnShow();
}
int main()
{
Composite* root = new Composite("root");
root->Add(new Leaf("leaf1"));
root->Add(new Leaf("leaf2"));
Composite* treeNode1 = new Composite("treeNode1");
root->Add(new Leaf("leaf3"));
root->Add(new Leaf("leaf4"));
Composite* treeNode2 = new Composite("treeNode2");
root->Add(new Leaf("leaf5"));
root->Add(new Leaf("leaf6"));
root->OnShow();
system("pause");
return 0;
}
打印结果:
Composite name: root
Leaf name: leaf1
Leaf name: leaf2
Leaf name: leaf3
Leaf name: leaf4
Leaf name: leaf5
Leaf name: leaf6
个人总结
1) Composite模式采用树形结构来实现普遍存在的对象容器,从而将"一对多"的关系转换为"一对一"的关系。
2) Composite的核心思想是客户代码和复杂的对象容器结构解耦。