组合模式:输出树形结构

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值