1.应用:主要应用于让关系型数据建立良好的树形关系
1:所有元素,包括Node,Leaf都继承自Component
这样,我们就拥有了所有Node,Leaf的共同特征.
2.对于Node来说,它拥有管理子Node或者子Leaf的作用,所以,一般而言它拥有这三个API
3.对于Leaf而言,就仁者见仁了,如果没有特别的一般就是继承自Component的
4.如何确定你生成的是Node,和Leaf
你可以定义一个Type,在构造的时候直接确定了比如:
5.一个完整的例子
老师<-班长,副班长
班长<-学委,体委,宣传委员
副班长<-小组长a,b,c,d
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeTest2
{
class Program
{
static void Main(string[] args)
{
Node root = new Node("老师");
root.addNode(new Node("班长"));
root.addNode(new Node("副班长"));
//学委,体委,宣传委员,小组长a,b,c,d
root.NodeDic["班长"].addNode(new Leaf("学委"));
root.NodeDic["班长"].addNode(new Leaf("宣传委员"));
root.NodeDic["班长"].addNode(new Node("体委"));
root.NodeDic["副班长"].addNode(new Leaf("小组长a"));
root.NodeDic["副班长"].addNode(new Leaf("小组长b"));
root.NodeDic["副班长"].addNode(new Leaf("小组长c"));
root.NodeDic["副班长"].addNode(new Leaf("小组长d"));
root.NodeDic["班长"].NodeDic["体委"].addNode(new Leaf("体育小组长a"));
root.NodeDic["班长"].NodeDic["体委"].addNode(new Leaf("体育小组长b"));
getTreeInfo(root);
}
public static void getTreeInfo(Node co)
{
// co.doSomething();
foreach (Component m_Co in co.getNodeList())
{
if (m_Co.type == 1)
{
m_Co.doSomething();
getTreeInfo((Node)m_Co);
}
else
{
m_Co.doSomething();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeTest2
{
public abstract class Component
{
public int type;
public Component(string _name)
{
this.name = _name;
}
public virtual void doSomething() {
Console.WriteLine(this.name);
}
public string name;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeTest2
{
public class Leaf:Component
{
public Leaf(string _name)
: base(_name)
{
this.type = 2;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeTest2
{
public class Node : Component
{
/// <summary>
/// 子节点
/// </summary>
private List<Component> subNodeList = new List<Component>();
public Dictionary<string, Node> NodeDic = new Dictionary<string, Node>();
public List<Component> getNodeList()
{
return subNodeList;
}
public void addNode(Component _node)
{
this.subNodeList.Add(_node);
if (_node.type == 1)
{
this.NodeDic.Add(_node.name, (Node)_node);
}
}
public void deleteNode(Component _node)
{
this.subNodeList.Remove(_node);
}
public Node(string _name)
: base(_name)
{
this.type = 1;
}
}
}