组合模式 CompositePattern

复合模式应用实例
本文介绍了一个使用复合模式的示例程序,通过定义一系列简单的类来展示如何构建复杂的树形结构。核心类包括基本的节点类(Node)、叶节点类(Leef)及复合节点类(NodeElement),并演示了如何通过这些类创建层级结构,并遍历打印所有节点信息。

using System; using System.Collections; class Node { private string _Name; private string _Description; public Node(string name, string description) { _Name = name; _Description = description; } public string Name { get { return _Name; } } public string Description { get { return _Description; } } public virtual void addNode(Node node) { throw new Exception("未提供该功能"); } public virtual void removeNode(Node node) { throw new Exception("未提供该功能"); } public virtual void printInformation() { throw new Exception("未提供该功能"); } public virtual ArrayList getChildNodes() { throw new Exception("未提供该功能"); } public virtual NodeIterator createNodeIterator() { throw new Exception("未提供该功能"); } }

节点的抽象

using System; class Leef : Node { public Leef(string name, string description) : base(name, description) { } public override void printInformation() { Console.WriteLine("Leef-Name-" + base.Name + "-Description-" + base.Description); } }

节点抽象的实现A

using System; using System.Collections; class NodeElement : Node { private ArrayList _NodeList; public NodeElement(string name, string description) : base(name, description) { _NodeList = new ArrayList(); } public override ArrayList getChildNodes() { return _NodeList; } public override void addNode(Node node) { _NodeList.Add(node); } public override void removeNode(Node node) { foreach (Node n in _NodeList) { if (n.Name == node.Name && n.Description == n.Description) _NodeList.Remove(n); } } public override void printInformation() { foreach (Node n in _NodeList) { n.printInformation(); } } }

节点抽象的实现B

using System; using System.Collections.Generic; using System.Text; namespace CompositePattern { class Program { static void Main(string[] args) { Node root = new NodeElement("节点", "根节点"); Node em1 = new NodeElement("节点", "节点1"); Node em2 = new NodeElement("节点", "节点2"); Node leef1 = new Leef("叶子", "叶子1"); Node leef2 = new Leef("叶子", "叶子2"); Node leef3 = new Leef("叶子", "叶子3"); Node leef4 = new Leef("叶子", "叶子4"); Node leef5 = new Leef("叶子", "叶子5"); Node leef6 = new Leef("叶子", "叶子6"); root.addNode(em1); root.addNode(em2); em1.addNode(leef1); em1.addNode(leef2); em1.addNode(leef3); em2.addNode(leef4); em2.addNode(leef5); em2.addNode(leef6); root.printInformation(); Console.ReadKey(); } } }

调用代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值