What is the difference between association, aggregation and composition?

后端 未结 19 1874
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 01:44

What is the difference between association, aggregation, and composition? Please explain in terms of implementation.

相关标签:
19条回答
  • 2020-11-22 02:19

    From a post by Robert Martin in comp.object:

    Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.

    //[Example:]
    
    //|A|----------->|B|
    
    class A
    {
      private:
        B* itsB;
    };
    

    Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).

    //[Example:]
    
    //|Node|<>-------->|Node|
    
    class Node
    {
      private:
        vector<Node*> itsNodes;
    };
    

    The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.

    Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.

    //[Example:]
    
    //|Car|<#>-------->|Carburetor|
    
    class Car
    {
      public:
        virtual ~Car() {delete itsCarb;}
      private:
        Carburetor* itsCarb
    };
    
    0 讨论(0)
提交回复
热议问题