From 1550d371d4d9933834405fa1a0150dee4a1587e4 Mon Sep 17 00:00:00 2001 From: Yuki Date: Fri, 11 Apr 2025 19:36:39 +0800 Subject: [PATCH] feat: Composite Implemented a demo for the Composite. --- 09_composite.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ notes.md | 9 ++++++++ 2 files changed, 64 insertions(+) create mode 100644 09_composite.cpp diff --git a/09_composite.cpp b/09_composite.cpp new file mode 100644 index 0000000..45f1e4b --- /dev/null +++ b/09_composite.cpp @@ -0,0 +1,55 @@ +#include +#include +#include + +using namespace std; + +class Shape { +public: + virtual void draw() = 0; + virtual ~Shape() = default; +}; + +class Square : public Shape { +public: + virtual void draw() { + cout << "Square" << endl; + } +}; + +class Circle : public Shape { +public: + virtual void draw() { + cout << "Circle" << endl; + } +}; + +// Both derived from shape, so that they can be treated as same +class ShapeGroup : public Shape { + vector> shapes; +public: + void add_shape(shared_ptr item) { + shapes.push_back(item); + } + + virtual void draw() { + cout << "draw group" << endl; + for (auto item : shapes) { + item->draw(); + } + } +}; + + +int main() { + auto s1 = make_shared(); + auto s2 = make_shared(); + auto c1 = make_shared(); + auto sg = make_shared(); + + sg->add_shape(s1); + sg->add_shape(s2); + sg->add_shape(c1); + sg->draw(); +} + diff --git a/notes.md b/notes.md index 1bdc23b..61dc3e8 100644 --- a/notes.md +++ b/notes.md @@ -57,3 +57,12 @@ 桥接模式给出的解决方案是:“组合优于继承”。它通过将“形状”和“纹理”分别建模为独立的类层次结构,并在“形状”中组合一个“纹理”的引用,使两者的组合关系从原来的 `M * N` 转变为 `M + N`。这样可以自由扩展任意一侧,而无需影响另一侧。即使实现中可能仍需要 `M * N` 种行为(这是无法减少的),但是当一个纹理要改变时,也只需要改这个纹理类而不影响其他类。此外,这种组合关系是运行时决定的,因此可以动态地将不同的抽象与实现配对,增强了系统的灵活性。 在桥接模式中,抽象部分(也称为接口)定义的是高层的控制逻辑,而真正的工作则由被称为实现部分的组件完成。抽象层在调用时,会将具体任务委派给实现层,从而实现灵活的组合与运行时绑定。 + +## 组合模式(Composite) + +在实际开发中,我们经常需要将多个对象组织成一个整体来进行处理。例如,在一个绘图应用中,一个画板可能包含多个图形元素(如圆形、矩形、线条等),我们希望能够将这些元素打包成一个更大的组件,便于统一地移动、缩放或删除。 + +但这就引出一个问题:组件和基本元素类型不同,无法使用统一的接口进行操作,需要额外判断和处理。 + +组合模式正是为了解决这个问题。它的核心思想是:将对象组合成树形结构来表示“整体-部分”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。也就是说,我们可以将一个组件(由多个元素组成)当作一个普通元素一样来处理,统一操作接口,简化客户端代码。 +