组合模式

本文详细介绍了组合模式的概念,如何在对象抽象的树形表示中使用它来创建‘部分-整体’层次结构,并提供了源代码示例来说明如何在实际编程中实现这一模式,以及其在客户端统一处理组合结构中的所有对象的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组合模式让我们可以把相同的基类型的对象组合到树状结构中,其中的父节点包含同类型的子节点。这种树状结构形成“部分—整体”的层次结构。

何时使用:1想通过对象抽象的树形表示(部分-整体层次结构);
                  2想让客户端统一处理组合结构中的所有对象。

源代码

1、抽象类Component

public 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 Diaplay(int depth);

}

 

2、叶子节点Leaf 继承于Component

public 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 Diaplay(int depth)

    {

        Console.WriteLine(new string('-',depth)+name);

    }

}

 

3、组合类Composite继承于Component,拥有枝节点行为

public class Composite : Component

{

 

    List<Component> children;

 

    public Composite(string name)

        :base(name)

    {

        if (children == null)

        {

            children = new List<Component>();

        }

    }

 

    public override void Add(Component c)

    {

        this.children.Add(c);

    }

 

    public override void Remove(Component c)

    {

        this.children.Remove(c);

    }

 

    public override void Diaplay(int depth)

    {

        Console.WriteLine(new String('-',depth)+name);

        foreach (Component component in children)

        {

            component.Diaplay(depth + 2);

        }

    }

}

 

 

4、客户端代码

static void Main(string[] args)

{

    Composite root = new Composite("根节点root");

    root.Add(new Leaf("根上生出的叶子A"));

    root.Add(new Leaf("根上生出的叶子B"));

 

    Composite comp = new Composite("根上生出的分支CompositeX");

    comp.Add(new Leaf("分支CompositeX生出的叶子LeafXA"));

    comp.Add(new Leaf("分支CompositeX生出的叶子LeafXB"));

 

    root.Add(comp);

 

    Composite comp2 = new Composite("分支CompositeX生出的分支CompositeXY");

    comp2.Add(new Leaf("分支CompositeXY生出叶子LeafXYA"));

    comp2.Add(new Leaf("分支CompositeXY生出叶子LeafXYB"));

 

    comp.Add(comp2);

 

    root.Add(new Leaf("根节点生成的叶子LeafC"));

    Leaf leafD = new Leaf("leaf D");

    root.Add(leafD);

    root.Remove(leafD);

    root.Diaplay(1);

    Console.Read();

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值