通过叶子和枝干的组合,实现树结构,以便于完成功能模块的复用。
效果如下:
代码如下:
public class CompositeRun
{
public static void RunItem()
{
string name;
Composite one, item;
Composite root = new Composite("南极总公司");
name = "大洋洲分公司";
one = new Composite(name);
item = new leaf(name + "后勤");
one.Add(item);
item = new leaf(name + "战斗部");
one.Add(item);
name = "南洋分部";
Composite oneX = new Composite(name);
item = new leaf(name + "后勤");
oneX.Add(item);
item = new leaf(name + "战斗部");
oneX.Add(item);
one.Add(oneX);
root.Add(one);
name = "月球分公司";
one = new Composite(name);
item = new leaf(name + "后勤");
one.Add(item);
item = new leaf(name + "战斗部");
one.Add(item);
root.Add(one);
root.Display(0);
}
}
interface IComposite
{
void Add(Composite a);
void Remove(Composite a);
void Display(int depth);
}
public class Composite : IComposite
{
protected string _name;
protected List<Composite> childs;
public Composite(string name)
{
_name = name;
childs = new List<Composite>();
}
public virtual void Add(Composite a)
{
childs.Add(a);
}
public virtual void Remove(Composite a)
{
childs.Remove(a);
}
public virtual void Display(int depth)
{
Console.WriteLine(new string('-', depth*4) + _name + " Including:");
foreach (var item in childs)
{
item.Display(depth + 1);
}
}
}
public class leaf : Composite
{
public leaf(string name)
: base(name)
{ }
public override void Add(Composite a)
{
throw new Exception("Composite can not Add");
}
public override void Remove(Composite a)
{
throw new Exception("Composite can not Remove");
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth*4) + _name + " Run");
}
}