using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Composite
{
public abstract class Component
{
public abstract void Show();
//添加部件
public abstract void Add(Component component);
//删除部件
public abstract void Remove(Component component);
public string Name { get; set; }
}
public class Leaf : Component
{
public override void Add(Component component)
{
throw new NotImplementedException();
}
public override void Remove(Component component)
{
throw new NotImplementedException();
}
public override void Show()
{
Console.WriteLine(Name);
}
}
public class Node : Component
{
private List<Component> myChildren = new List<Component>();
public override void Add(Component component)
{
myChildren.Add(component);
}
public override void Remove(Component component)
{
myChildren.Remove(component);
}
public override void Show()
{
Console.WriteLine(Name);
foreach (Component child in myChildren)
{
child.Show();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Composite
{
class Program
{
static void Main(string[] args)
{
//构造根节点
Node rootComponent = new Node();
rootComponent.Name = "根节点";
//添加两个叶子几点,也就是子部件
Leaf l = new Leaf();
l.Name = "叶子节点一";
Leaf l1 = new Leaf();
l1.Name = "叶子节点二";
rootComponent.Add(l);
rootComponent.Add(l1);
rootComponent.Show();
Console.ReadLine();
}
}
}