组合模式

#include <iostream>
#include <list>
#include <memory>

class Component {
public:
    virtual void show() const = 0;
    virtual void add(const std::shared_ptr<Component> c) {};
};

class Leaf : public Component {
public:
    void show() const override { std::cout << "In leaf show()." << std::endl; }
};

class Composite : public Component {
public:
    void show() const override {
        std::cout << "In Composite show()." << std::endl;
        for (const auto& c : lc) {
            c->show();
        }
    }
    void add(const std::shared_ptr<Component> c) override { lc.push_back(c); }
private:
    std::list<std::shared_ptr<Component>> lc;
};

int main(int argc, char *argv[]) {
    std::unique_ptr<Component> t = std::make_unique<Composite>();
    std::shared_ptr<Component> l1 = std::make_shared<Composite>();
    std::shared_ptr<Component> l2 = std::make_shared<Leaf>();
    l1->add(l2);
    t->add(l1);
    t->add(l2);
    t->show();
    return 1;
}

  

posted @ 2022-02-25 17:49  南乡水  阅读(20)  评论(0编辑  收藏  举报