组合模式,宏指令和普通指令的聚合应用(设计模式与开发实践 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();
    }
}

抽象类

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

文件系统常用

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

相关推荐
李宥小哥14 小时前
结构型设计模式1
设计模式
lapiii35814 小时前
[智能体设计模式] 第五章 :函数调用
microsoft·设计模式
lapiii35814 小时前
[智能体设计模式] 第 1 章:提示链(Prompt Chaining)
设计模式·prompt
昨天的猫15 小时前
《拒绝重复代码!模板模式教你优雅复用算法骨架》
后端·设计模式
L.EscaRC15 小时前
ArkTS分布式设计模式浅析
分布式·设计模式·arkts
Arva .16 小时前
责任链设计模式->规则树
设计模式
WKP941817 小时前
命令设计模式
设计模式
lapiii35821 小时前
[智能体设计模式] 第4章:反思(Reflection)
人工智能·python·设计模式
颜酱1 天前
理解编程范式(前端角度)
设计模式
将编程培养成爱好1 天前
C++ 设计模式《账本事故:当备份被删光那天》
开发语言·c++·设计模式·备忘录模式