gpt4 book ai didi

c# - 复合模式简化

转载 作者:行者123 更新时间:2023-11-30 14:20:02 26 4
gpt4 key购买 nike

如果不实现组件并将所有内容都视为组合,我会失去什么?

我已经放弃了叶节点的实现:

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);
}
}
}

复合模式的这种方法有什么问题?这种设计会遇到什么样的问题?

最佳答案

您将放弃任何子类化“叶子”的机会,如果事实证明您有不同类型的“节点”,您可能最终会以一种或另一种方式污染结构。而且您也违反了单一责任原则。使用复合模式非常很容易造成各种污染,我认为干净利落地做到这一点总是值得的。

关于c# - 复合模式简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1781295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com