Design Pattern --- Composite
qingwenclass Component { public: virtual void foo() = 0; }; class LeafA : public Component { public: // Interface. virtual void foo() override { cout <<"LeafA::foo()." <<endl; } }; class LeafB : public Component { public: // Interface. virtual void foo() override { cout <<"LeafB::foo()." <<endl; } }; class Composite : public Component { // data. vector<Component *> m_components; public: // Interface. virtual void foo() override { for (auto i : m_components) { i->foo(); } } void add(Component *component) { m_components.push_back(component); } }; int main(int argc, char *argv[]) { Composite *c1 = new Composite, *c2 = new Composite, *c = new Composite; c1->add(new LeafA); c2->add(new LeafA), c2->add(new LeafB); c->add(c1), c->add(c2); // 这里体现了 Composite 模式的优势。 // 不区别对待单个 Leaf 和 Composite。 // 使得递归每一个 Component 变得容易。 c->foo(); return 0; }