组合模式:输出树形结构

来源:互联网 发布:中小学教育网网络课程 编辑:程序博客网 时间:2024/05/23 23:18

1.节点类

namespace CombinationPattern
{
    /* 组合模式:当对象或系统之间出现部分与整体,或类似树状结构的
     * 情况时,考虑组合模式。相对装饰模式来说,这两个有异曲同工
     * 之妙,都强调对象间的组合,但是,装饰模式同时强调组合的顺
     * 序,而组合模式则是随意组合与移除
     */
    public abstract class Node 
    {
        /// <summary>
        /// 节点名称
        /// </summary>
        public string NodeName;

        public Node(string nodeName)
        {
            NodeName = nodeName;
        }

        public abstract void AddNode(Node node);
        public abstract void RemoveNode(Node node);
        public abstract void ShowCurrentDepth(int depth);
    }

    public class Leaf : Node
    {
        public Leaf(string nodeName)
            : base(nodeName)
        { }

        public override void AddNode(Node node)
        {
            Console.WriteLine("不要在{0}节点上添加子节点",NodeName);
        }

        public override void RemoveNode(Node node)
        {
            Console.WriteLine("不要在{0}节点上移除子节点", NodeName);
        }

        public override void ShowCurrentDepth(int depth)
        {
            Console.WriteLine(new String(' ', depth) + NodeName);
        }
    }

    public class BranchNode : Node
    {
        public List<Node> list = new List<Node>();

        public BranchNode(string nodeName)
            : base(nodeName)
        { }

        public override void AddNode(Node node)
        {
            list.Add(node);
        }

        public override void RemoveNode(Node node)
        {
            list.Remove(node);
        }

        public override void ShowCurrentDepth(int depth)
        {
            Console.WriteLine(new String(' ', depth) + NodeName);//用于显示当前节点

            foreach (var tmp in list)
                tmp.ShowCurrentDepth(depth + 2);
        }
    }
}

2.调用

static void Main(string[] args)
        {
            BranchNode branchNodeA = new BranchNode("根节点A");
            branchNodeA.AddNode(new Leaf("节点A1"));
            branchNodeA.AddNode(new Leaf("节点A2"));

            BranchNode branchNodeB = new BranchNode("根节点B挂在A上");
            branchNodeB.AddNode(new Leaf("节点B1"));
            branchNodeB.AddNode(new Leaf("节点B2"));

            branchNodeA.AddNode(branchNodeB);

            BranchNode branchNodeC = new BranchNode("根节点C挂在B上");
            branchNodeC.AddNode(new Leaf("节点C1"));
            branchNodeC.AddNode(new Leaf("节点C2"));

            branchNodeB.AddNode(branchNodeC);

            branchNodeA.AddNode(new Leaf("节点D直接挂在A上"));

            Leaf leaf = new Leaf("节点E");
            branchNodeA.AddNode(leaf);
            Leaf leafF = new Leaf("节点F");
            leaf.AddNode(leafF);
            //branchNodeA.RemoveNode(branchNodeB);
            branchNodeA.ShowCurrentDepth(1);

            Console.ReadKey();
        }