验证中...
开源中国 2018 年度最后一场技术盛会邀你来约~错过就要等明年啦!点此立即预约
片段 1 片段 2
component.cs
原始数据 复制代码
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("不可以在叶子上加东西");
}
public override void Remove(Component c)
{
Console.WriteLine("不可以在叶子下面删除东西");
}
public override void Display(int depth)
{
Console.WriteLine(new string('-',depth)+this.name);
}
}
class Composite:Component
{
private List<Component> children=new List<Component>();
public Composite(string name)
: base(name)
{
}
public override void Add(Component c)
{
this.children.Add(c);
}
public override void Remove(Component c)
{
this.children.Remove(c);
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + this.name);
foreach (Component theComponent in this.children)
{
theComponent.Display(depth+2);
}
}
}
program.cs
原始数据 复制代码
class Program
{
static void Main(string[] args)
{
Composite root=new Composite("root");
root.Add(new Leaf("叶子A"));
root.Add(new Leaf("叶子B"));
Composite theComposite1=new Composite("树枝X");
theComposite1.Add(new Leaf("叶子XA"));
theComposite1.Add(new Leaf("叶子XB"));
root.Add(theComposite1);
Composite theComposite2 = new Composite("树枝XY");
theComposite2.Add(new Leaf("叶子XYA"));
theComposite2.Add(new Leaf("叶子XYB"));
theComposite1.Add(theComposite2);
root.Add(new Leaf("叶子C"));
Leaf leaf=new Leaf("叶子D");
root.Add(leaf);
root.Remove(leaf);
root.Display(1);
Console.ReadKey();
}
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助