标签:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
组合模式
*
* 树型节点管理
*/
namespace App_MYCS.HDL_SJMS.ZHMS
{
class my_ZHMS
{
public void dy()
{
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 Y");
comp2.Add(new Leaf("leaf Ya"));
comp2.Add(new Leaf("leaf Yb"));
comp.Add(comp2);
root.Add(new Leaf("leaf c"));
root.Display(1);
}
}
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);//显示
//扩展
}
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 to a leaf");
}
public override void Display(int depth)//显示
{
Console.WriteLine(new String(‘-‘,depth)+name);//叶节点的具体方法 显示名称和级别
}
}
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);//叶节点的具体方法 显示名称和级别
if (children != null && children.Count > 0)
{
foreach (Component cp in children)
{
cp.Display(depth + 2);
}
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/longkai178/p/5815127.html