What is the difference between association, aggregation and composition?

后端 未结 19 1869
伪装坚强ぢ
伪装坚强ぢ 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:10

    As others said, an association is a relationship between objects, aggregation and composition are types of association.

    From an implementation point of view, an aggregation is obtained by having a class member by reference. For example, if class A aggregates an object of class B, you'll have something like this (in C++):

    class A {
        B & element;
      // or B * element;
    };
    

    The semantics of aggregation is that when an object A is destroyed, the B object it is storing will still exists. When using composition, you have a stronger relationship, usually by storing the member by value:

    class A {
        B element;
    };
    

    Here, when an A object is destroyed, the B object it contains will be destroyed too. The easiest way to achieve this is by storing the member by value, but you could also use some smart pointer, or delete the member in the destructor:

    class A {
        std::auto_ptr element;
    };
    
    class A {
        B * element;
    
        ~A() {
            delete B;
        }
    };
    

    The important point is that in a composition, the container object owns the contained one, whereas in aggregation, it references it.

提交回复
热议问题