如果不实现组件并将所有内容都视为组合,我会失去什么?
我已经放弃了叶节点的实现:
IE
class Component : IComponent
{
/*...*/
}
现在请看看我的代码。
public interface IComponent
{
int ID { get;set; }
string Name { get;set;}
void Add(IComponent item);
void Remove(IComponent item);
List<IComponent> Items { get; }
void Show();
}
public class Composite : IComponent
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Composite(int id, string name)
{
_id = id;
_name = name;
}
private List<IComponent> _items = new List<IComponent>();
public void Add(IComponent item)
{
_items.Add(item);
}
public void Remove(IComponent item)
{
_items.Remove(item);
}
public List<IComponent> Items
{
get
{
return new List<IComponent>(_items);
}
}
public void Show()
{
Console.WriteLine("ID=" + _id + "; Name=" + _name);
}
}
class Program
{
static void Main(string[] args)
{
IComponent root = new Composite(1, "World");
IComponent asia = new Composite(2, "Asia");
IComponent europe = new Composite(3, "Europe");
root.Add(asia);
root.Add(europe);
asia.Add(new Composite(4, "China"));
asia.Add(new Composite(5, "Japan"));
europe.Add(new Composite(6, "Germany"));
europe.Add(new Composite(7, "Russia"));
root.Show();
Program.Traverse(root.Items);
Console.ReadLine();
}
static void Traverse(List<IComponent> items)
{
foreach (IComponent c in items)
{
c.Show();
Traverse(c.Items);
}
}
}
这种复合模式的方法有什么问题?这种类型的设计我会面临什么样的问题?