23种设计模式(十九)数据结构之组合模式

    科技2022-08-14  82

    本系列所有文章来自李建忠老师的设计模式笔记,系列如下: 设计模式(一)面向对象设计原则 23种设计模式(二)组件协作之模板方法 23种设计模式(三)组件协作之策略模式 23种设计模式(四)组件协作之观察者模式 23种设计模式(五)单一职责之装饰模式 23种设计模式(六)单一职责之桥模式 23种设计模式(七)对象创建之工厂方法 23种设计模式(八)对象创建之抽象工厂 23种设计模式(九)对象创建之原型模式 23种设计模式(十)对象创建之构建器 23种设计模式(十一)对象性能之单件模式 23种设计模式(十二)对象性能之享元模式 23种设计模式(十三)接口隔离之门面模式 23种设计模式(十四)接口隔离之代理模式 23种设计模式(十五)接口隔离之适配器 23种设计模式(十六)接口隔离之中介者 23种设计模式(十七)状态变化之状态模式 23种设计模式(十八)状态变化之备忘录 23种设计模式(十九)数据结构之组合模式 23种设计模式(二十)数据结构之迭代器 23种设计模式(二十一)数据结构之职责链 23种设计模式(二十二)行为变化之命令模式 23种设计模式(二十三)行为变化之访问器 23种设计模式(二十四)领域规则之解析器

    文章目录

    数据结构模式动机模式定义代码要点总结

    数据结构模式

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

    动机

      软件在某些情况下,客户代码过多地依赖于对象容器复杂的内部实现结构,对象容器内部实现结构(而非抽象接口)的变化将引起客户代码的频繁变化,带来了代码的维护性、扩展性等弊端。

    模式定义

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

    代码

    #include <iostream> #include <list> #include <string> #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(){ //1. process current node //2. process leaf nodes for (auto &e : elements) e->process(); //多态调用 } }; //叶子节点 class Leaf : public Component{ string name; public: Leaf(string s) : name(s) {} void process(){ //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 leat1("left1"); Leaf leat2("left2"); root.add(&treeNode1); treeNode1.add(&treeNode2); treeNode2.add(&leaf1); root.add(&treeNode3); treeNode3.add(&treeNode4); treeNode4.add(&leaf2); process(root); process(leaf2); process(treeNode3); }

    要点总结

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

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

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

    Processed: 0.011, SQL: 9