Skip to content

组合(Composite)模式 结构型模式

将对象组合成树状层次结构,使用户对单个对象和组合对象具有一致的访问性。

c#
// 组合模式示例
using System;
using System.Collections.Generic;

// 抽象类,定义了组合中的对象和方法
abstract class Component
{
    protected string name;
    public Component(string name)
    {
        this.name = name;
    }
    public abstract void Add(Component c);
    public abstract void Remove(Component c);
    public abstract void Display(int depth);
}

// 叶子节点,没有子节点
class Leaf : Component
{
    public Leaf(string name) : base(name)
    {
    }
    public override void Add(Component c)
    {
        Console.WriteLine("不能添加到叶子节点");
    }
    public override void Remove(Component c)
    {
        Console.WriteLine("不能从叶子节点删除");
    }
    public override void Display(int depth)
    {
        Console.WriteLine(new String('-', depth) + name);
    }
}

// 复合节点,可以包含子节点
class Composite : Component
{
    private List<Component> children = new List<Component>();
    public Composite(string name) : base(name)
    {
    }
    public override void Add(Component c)
    {
        children.Add(c);
    }
    public override void Remove(Component c)
    {
        children.Remove(c);
    }
    public override void Display(int depth)
    {
        Console.WriteLine(new String('-', depth) + name);
        foreach (Component component in children)
        {
            component.Display(depth + 2);
        }
    }
}

// 客户端代码
class Client
{
    static void Main(string[] args)
    {
        // 创建根节点
        Composite root = new Composite("根节点");

        // 创建子节点
        Composite branch1 = new Composite("分支1");
        Composite branch2 = new Composite("分支2");

        // 创建叶子节点
        Leaf leaf1 = new Leaf("叶子1");
        Leaf leaf2 = new Leaf("叶子2");
        Leaf leaf3 = new Leaf("叶子3");

        // 将子节点和叶子节点添加到根节点和分支节点中
        root.Add(branch1);
        root.Add(branch2);
        branch1.Add(leaf1);
        branch2.Add(leaf2);
        branch2.Add(leaf3);

        // 显示树形结构
        root.Display(1);

        Console.ReadKey();
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度