
复合模式是业界使用最广泛的模式之一,它解决了一个非常重要且微妙的问题。 每当用户想要以与单个对象集合相同的方式对待单个对象时,就使用它,例如,您可能希望将副本中的页面视为与整个副本相同的页面,而整个副本基本上是页面的集合,或者 如果要创建某些事物的层次结构,则可能需要将整个事物视为对象。
将对象组合成树结构以表示部分-整体层次结构。Composite允许客户端统一处理单个对象和对象的组合。
在photoshop中,我们绘制许多单个对象,然后这些对象组成一个完整的唯一对象,您可能要对整个对象而不是每个单个对象应用某些操作。

在这个图中,您可以看到composite和Leaf都实现了组件图,因此允许对这两个对象执行相同的操作,但重要的部分是composite类,它还包含组件对象,组件对象由表示composite和组件类之间的组合关系的黑色菱形表示。
然后如何设计我们的类来适应这样的场景。我们将尝试通过实现我们的复制示例来理解它。假设您必须创建一个具有添加、删除、拷贝等操作的页面,以及一个具有与单个页面相同操作的副本。
这种情况最好用复合模式处理。
// CPP program to illustrate
// Composite design pattern
#include <iostream>
#include <vector>
using namespace std;
class PageObject {
public:
virtual void Add(PageObject a)
{
}
virtual void Remove()
{
}
virtual void Delete(PageObject a)
{
}
};
class Page : public PageObject {
public:
void Add(PageObject a)
{
cout << "something is added to the page" << endl;
}
void Remove()
{
cout << "soemthing is removed from the page" << endl;
}
void Delete(PageObject a)
{
cout << "soemthing is deleted from page " << endl;
}
};
class Copy : public PageObject {
vector<PageObject> copyPages;
public:
void AddElement(PageObject a)
{
copyPages.push_back(a);
}
void Add(PageObject a)
{
cout << "something is added to the copy" << endl;
}
void Remove()
{
cout << "something is removed from the copy" << endl;
}
void Delete(PageObject a)
{
cout << "something is deleted from the copy";
}
};
int main()
{
Page a;
Page b;
Copy allcopy;
allcopy.AddElement(a);
allcopy.AddElement(b);
allcopy.Add(a);
a.Add(b);
allcopy.Remove();
b.Remove();
return 0;
}
something is added to the copy
something is added to the page
something is removed from the copy
soemthing is removed from the page
现在,可以应用于单个对象并且也可以应用于这些单个对象的集合的相同操作,使得使用较小的独立对象组成的较大对象变得非常容易。
复合模式的最显着示例是在任何UI工具包中。考虑UI元素的情况,其中每个UI顶级UI元素由许多较小的独立的下层UI元素组成,并且上层和下层UI元素都响应相同的事件和动作。