关闭

组合模式

112人阅读 评论(0) 收藏 举报
分类:

Component.cs

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);
}

Composite.cs

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);
        }
    }
}

Leaf.cs

class Leaf:Component
{
    public Leaf(String name) : base(name)
    {

    }

    public override void Add(Component c)
    {
        Console.WriteLine("Cannot add to a leaf");
    }

    public override void Remove(Component c)
    {
        Console.WriteLine("Cannot remove on a leaf");
    }

    public override void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + name);
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite comp = new Composite("Composite X");
        comp.Add(new Leaf("Leaf XA"));
        comp.Add(new Leaf("Leaf XB"));

        root.Add(comp);

        Composite comp2 = new Composite("Composite XY");
        comp2.Add(new Leaf("Leaf XYA"));
        comp2.Add(new Leaf("Leaf XYB"));

        root.Add(comp2);

        root.Add(new Leaf("Leaf C"));

        Leaf leaf = new Leaf("Leaf D");
        root.Add(leaf);
        root.Remove(leaf);

        root.Display(1);

        Console.Read();
    }
}

运行结果:
这里写图片描述

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:112376次
    • 积分:2948
    • 等级:
    • 排名:第12378名
    • 原创:188篇
    • 转载:5篇
    • 译文:1篇
    • 评论:23条
    博客专栏
    最新评论