设计模式-组合模式-笔记

"数据结构"模式

常常有一些组件在内部具有特定的数据结构,如果让客户程序依赖这些特定数据结构,将极大地破坏组件的复用。这时候,将这些特定数据结构封装在内部,在外部提供统一的接口,来实现与特定数据结构无关的访问,是一种行之有效的解决方案。

经典模式:Composite、Iterator、Chain of resposibility

动机(Motivation)

将对象组合成树形结构以代表"部分-整体"的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性(稳定)。

示例:

cpp 复制代码
#include <string>
#include <list>
#include <algorithm>

using namespace std;

class Component {
public:
    virtual void process() = 0;
    virtual ~Component() {}
};

//树节点
class Composite : public Component {
    string name_;
    list<Component*> elements_;
public:
    Composite(const string& s) : name_(s) {}
    void add(Component* element) {
        elements_.push_back(element);
    }
    void remove(Component* element) {
        elements_.remove(element);
    }

    void process() override {
        //1.process curent node

        //2.process leaf nodes
        for (auto& e : elements_){
            e->process();   //虚函数调用,多态调用
        }
    }
};

//叶子节点
class Leaf : public Component {
    string name_;
public:
    Leaf(const string&s) : name_(s) {}

    void process() override  {
        //process current node
    }
};

//客户程序
void invoke(Component& c) {
    //...
    c.process();
    //...
}

int main() {

    Composite root("root");
    Composite treeNode1("treeNode1");
    Composite treeNode2("treeNode2");
    Composite treeNode3("treeNode3");
    Composite treeNode4("treeNode4");
    Leaf leaf1("leaf1");
    Leaf leaf2("leaf2");

    root.add(&treeNode1);
    treeNode1.add(&treeNode2);
    treeNode2.add(&leaf1);

    root.add(&treeNode3);
    treeNode3.add(&treeNode4);
    treeNode4.add(&leaf2);

    invoke(root);
    invoke(leaf2);
    invoke(treeNode3);
}

要点总结:

Composite模式采用采用树形结构来实现普遍存在的对象容器,从而将"一对多"的关系转化为"一对一"的关系,使得客户代码可以一致地(复用)处理对象和对象容器,无需关系处理的是单个的对象,还是组合的对象容器。

将"客户代码与复杂的对象容器结构"解耦是Composite的核心思想,解耦之后,客户代码将与纯粹的抽象接口----而非对象容器的内部实现结构----发生依赖,从而更能"应对变化"。

COmposite模式在具体实现中,可以让父对象中的子对象反向追溯;如果父对象有频繁的遍历需求,可使用缓存技巧来改善效率。

相关推荐
寻丶幽风2 小时前
论文阅读笔记——双流网络
论文阅读·笔记·深度学习·视频理解·双流网络
君鼎2 小时前
C++设计模式——单例模式
c++·单例模式·设计模式
敲代码的 蜡笔小新3 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
令狐前生3 小时前
设计模式学习整理
学习·设计模式
敲代码的 蜡笔小新6 小时前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式
JANYI20186 小时前
嵌入式设计模式基础--C语言的继承封装与多态
java·c语言·设计模式
sz66cm7 小时前
Linux基础 -- SSH 流式烧录与压缩传输笔记
linux·笔记·ssh
开发游戏的老王8 小时前
[虚幻官方教程学习笔记]深入理解实时渲染(An In-Depth Look at Real-Time Rendering)
笔记·学习·虚幻
愚润求学9 小时前
【Linux】Ext系列文件系统
linux·运维·服务器·笔记
敲代码的 蜡笔小新10 小时前
【行为型之观察者模式】游戏开发实战——Unity事件驱动架构的核心实现策略
观察者模式·unity·设计模式·c#