组合模式,宏指令和普通指令的聚合应用(设计模式与开发实践 P10)

文章目录

程序设计中有一些 事物是由相似的子事物 构成的例子

定义

回顾过去的命令模式,有一些命令里面包含了一个序列的操作,如果你玩魔兽世界或者类似的 MMO 游戏,里面你会用到 宏指令,就是一个指令包含了一系列操作

那么这个 Macro Command 整合了几个不同的指令对象,形成了一个 树状结构 ,这就使得我们可以方便地描述 对象部分-整体层次结构 了

举例

这里使用 C# 举例,叶子和容器都属于 Component 类,具有多态性 又具有统一性 ,所以客户调用时无需关注调用的是 组合 还是 子对象!

csharp 复制代码
using System;
using System.Collections.Generic;

// 组件接口
public abstract class Component
{
    protected string name;

    public Component(string name)
    {
        this.name = name;
    }

    public abstract void PerformAction();
}

// 叶子组件
public class Leaf : Component
{
    public Leaf(string name) : base(name)
    {
    }

    public override void PerformAction()
    {
        Console.WriteLine($"执行{name}的操作");
    }
}

// 容器组件
public class Composite : Component
{
    private List<Component> children;

    public Composite(string name) : base(name)
    {
        children = new List<Component>();
    }

    public void Add(Component component)
    {
        children.Add(component);
    }

    public void Remove(Component component)
    {
        children.Remove(component);
    }

    public override void PerformAction()
    {
        Console.WriteLine($"执行{name}的操作");
        
        foreach (var child in children)
        {
            child.PerformAction();
        }
    }
}

// 使用示例
class Program
{
    static void Main(string[] args)
    {
        // 创建组件对象
        var root = new Composite("家庭");
        var parent1 = new Composite("父母");
        var parent2 = new Composite("叔叔");

        var child1 = new Leaf("孩子1");
        var child2 = new Leaf("孩子2");
        var child3 = new Leaf("孩子3");

        // 构建组件树
        root.Add(parent1);
        root.Add(parent2);
        parent1.Add(child1);
        parent1.Add(child2);
        parent2.Add(child3);

        // 执行操作
        root.PerformAction();

        Console.ReadLine();
    }
}

抽象类

上面说到多态性和统一性,组合模式最大的优点就是可以一致地对待组合对象和基本对象,用户只需要知道他是一个命令,不需要知道他是 宏命令 还是 普通命令

文件系统常用

文件夹和文件之间的关系很适合用组合模式来描述,文件夹里面可以有 文件夹 也可以有 文件,最终可以组合成一棵树~

相关推荐
阿狗童鞋6 小时前
设计模式实战指南
设计模式
电子科技圈11 小时前
基于车载SerDes和OpenGMSL协议的SoC设计与验证:行业高频问题解析
设计模式·车载系统·软件构建·设计规范
ClinicTech13 小时前
高速冷冻离心机的温控系统与安全保护逻辑解析
设计模式·架构·健康医疗·设计语言
GISMagic17 小时前
3.《设计模式》:软件设计与解耦能力提炼
设计模式·ai coding
染指111017 小时前
131.Agent-Agent设计模式-MAS多智能体系统(Multi-Agent-System)
人工智能·设计模式·langchain·agent·agents
ShyanZh1 天前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
YYYing.2 天前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++
长按助力退休2 天前
设计模式实战,这 5 个最常用
设计模式
Carl_奕然2 天前
【智能体】Agent的四种设计模式之:Multi-Agent Collaboration
设计模式
Lost of 程序猿2 天前
建造者模式实战:告别“十参数构造函数“的数据导出任务
后端·设计模式·c#·asp.net