2009-04-17 163 views

回答

20

這是一個相當抽象的問題,因爲這兩個組成&聚集很相似&真的只在概念上不同,不一定在代碼級別上。 (也就是說,你可能會認爲一輛汽車有一臺發動機是組成的,而一隻狗有跳蚤要聚合,但如果你用代碼模擬它們,就沒有什麼能阻止你以同樣的方式實現它們)。

但是,如果你想打破差異&嘗試&強行添加軟件的設計來突出那些我想你可以做這樣的事情......採取an example from Wikipedia差異:

聚集與普通的不同因爲它並不意味着所有權。在構圖中,當擁有的對象被破壞時,被包含的對象也被破壞。在聚合中,這不一定是真實的。例如,一所大學擁有各個部門(如化學),每個部門都有一些教授。如果大學關閉,部門將不復存在,但這些部門的教授將繼續存在。因此,大學可以被看作是一個部門的組成部分,而部門則由教授組成。此外,一位教授可以在多個部門工作,但一個部門不能成爲不止一個大學的一部分。

你可能會建立這個代碼來表示它(與組成/聚集儘可能多的做作適應症):

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 
{ 
} 
+3

老問題,但我偶然發現了它,我只是建議,如果部門是要只有合成,你可以通過讓它成爲大學內部的嵌套類並將其私有化來強制執行。因此,使任何其他地方甚至可以宣佈一個部門並明確地表明父母/子女關係。 – 2012-02-02 04:28:32

5

那麼,在所有對象都通過嚴格的組成和聚集模糊一點之間的引用,微妙的差別(所有權)訪問的垃圾收集世界 - 所以一般(當使用類),它歸結爲一個字段爲其他對象或集合:

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;} 
    //... 
} 

如果我錯了,請澄清...

事情更復雜,當你討論struct秒 - 但一般談到面向對象的概念時,struct使用僅限於值字段...