问题描述
我如何/(什么是最好的方式)实现在C#中的组成和聚集?
How do I/(what is the best way to) implement composition and aggregation in C#?
由于
123Developer
Thanks123Developer
推荐答案
这是一个非常抽象的问题,因为这两种成分和放大器;聚集很相似&安培;真的只有不同的概念,而不一定在代码级别。 (例如,你可能会考虑汽车具有发动机是组成,和狗有跳蚤是聚集,但没有什么阻止你以同样的方式执行他们,如果你是他们中的代码建模)。
That's a pretty abstract question, given that both composition & aggregation are pretty similar & really only different conceptually and not necessarily at the code level. (i.e. you might consider a Car having an Engine to be composition, and a Dog having fleas to be aggregation, but there's nothing stopping you implementing them in the same way if you were modelling them in code).
不过,如果你想打破的差异和放大器;尝试和放大器;强行添加软件设计决策要突出那些我想你可以做这样的事情的差异......采取一个例子/一个>:
However, if you want to break down the differences & try & forcibly add software design decisions to highlight those differences I guess you could do something like this... taking an example from Wikipedia:
聚集之处在于它不意味着所有普通组合物不同。在构图,当拥有对象被销毁,所以都包含的对象。在聚集,这未必是真实的。例如,一所大学拥有各部门(例如,化学),以及每个部门都有多位教授。如果大学关闭,各部门将不再存在,但是在这些部门的教授将继续存在。因此,大学可以看作部门的组合物,而部门有教授的集合。此外,一个教授可以在多个部门工作,而是一个部门不能超过一个大学的一部分。
您可以建立这样的代码来表示它(与组合式/聚集尽可能多的做作适应症):
You might build this code to represent it (with as many contrived indications of composition/aggregation):
public class University : IDisposable
{
private IList<Department> departments = new List<Department>();
public void AddDepartment(string name)
{
//Since the university is in charge of the lifecycle of the
//departments, it creates them (composition)
departments.Add(new Department(this, name));
}
public void Dispose()
{
//destroy the university...
//destroy the departments too... (composition)
foreach (var department in departments)
{
department.Dispose();
}
}
}
public class Department : IDisposable
{
//Department makes no sense if it isn't connected to exactly one
//University (composition)
private University uni;
private string name;
//list of Professors can be added to, meaning that one professor could
//be a member of many departments (aggregation)
public IList<Professor> Professors { get; set; }
// internal constructor since a Department makes no sense on its own,
//we should try to limit how it can be created (composition)
internal Department(University uni, string name)
{
this.uni = uni;
this.name = name;
}
public void Dispose()
{
//destroy the department, but let the Professors worry about
//themselves (aggregation)
}
}
public class Professor
{
}
这篇关于实现在C#中的组成和聚集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!