Alc*_*nja 20
这是一个非常抽象的问题,因为组合和聚合都非常相似,并且在概念上实际上只是不同而不一定在代码级别.(也就是说,你可能会认为一辆汽车有一个发动机组成,一只狗有跳蚤聚合,但如果你用代码建模它们就没有什么能阻止你以相同的方式实现它们).
但是,如果你想分解差异并尝试并强行添加软件设计决策以突出这些差异,我想你可以做这样的事情......以维基百科为例:
聚合与普通组成的不同之处在于它并不意味着所有权.在组合中,当拥有对象被破坏时,包含的对象也被破坏.在汇总中,这不一定是真的.例如,一所大学拥有各个部门(例如化学),每个部门都有一些教授.如果大学关闭,部门将不复存在,但这些部门的教授将继续存在.因此,大学可以被视为一个部门的组合,而部门则有教授的集合.此外,教授可以在多个部门工作,但一个部门不能成为一个以上大学的一部分.
您可以构建此代码来表示它(使用尽可能多的人为组合/聚合的指示):
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
{
}
Run Code Online (Sandbox Code Playgroud)
好吧,在通过引用访问所有对象的垃圾收集世界中,严格组合和聚合之间的细微差别(所有权)模糊了一点 - 所以一般情况下(当使用类时)它归结为另一个对象的字段或采集:
class Building {
private readonly List<Room> rooms = new List<Room>();
public IList<Room> Rooms {get {return rooms;}}
public Address Address {get;set;}
//...
}
class Address {
public string Line1 {get;set;}
public string PostCode {get;set;}
//...
}
class Room {
public string Name {get;set;}
public int Capacity {get;set;}
//...
}
Run Code Online (Sandbox Code Playgroud)
如果我错过了这一点,请澄清......
当你讨论structs 时,事情会更复杂- 但通常在谈论OO概念时,struct使用仅限于价值领域......