如果不执行组件并将所有对象视为组合,我会失去什么?复合模式简化
我已经放弃了对叶节点的实现:
即
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);
}
}
}
什么是错的组合模式的这种做法?这种类型的设计可以面对什么样的问题?
您可能会考虑澄清一下,您的问题是“通过不执行组件并将所有内容视为组合件而失去了什么”......我最初认为您的代码有问题,并且意识到您的问题不是关于代码,其中的“作品”,但为什么你应该添加叶:) – Mathias 2009-11-23 06:04:05
建议你在这里研究代码示例和内容:http://www.dofactory.com/patterns/patterncomposite.aspx看不到任何理由你应该“放弃Leaf节点的实现”。祝你好运 ! – BillW 2009-11-23 06:11:25