What is the difference between association, aggregation and composition?

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

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

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

    From: Remo H. Jansen book “Beginning React: Learning TypeScript 2.x - Second Edition” :

    We call association those relationships whose objects have an independent life cycle where there is no ownership of the objects. Let's take a look at an example of a teacher and a student. Multiple students can be associated with a single teacher, and a single student can be associated with multiple teachers, but both have independent life cycles (both can create and delete independently). So, when a teacher leaves the school, we don't need to delete any students, and when a student leaves the school, we don't need to delete any teachers.

    We call aggregation those relationships whose objects have an independent life cycle, but there is ownership, and child objects cannot belong to another parent object. Let's take an example of a cell phone and a cell phone battery. A single battery can belong to a phone, but if the phone stops working, and we delete it from our database, the phone battery will not be deleted because it may still be functional. So, in aggregation, while there is ownership, objects have their life cycle

    We use the term composition to refer to relationships whose objects don't have an independent life cycle, and if the parent object is deleted, all child objects will also be deleted. Let's take an example of the relationship between questions and answers. Single questions can have multiple answers, and answers cannot belong to multiple questions. If we delete questions, answers will automatically be deleted.

    0 讨论(0)
  • 2020-11-22 01:57

    Association is generalized concept of relations. It includes both Composition and Aggregation.

    Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures

    Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.

    Both denotes relationship between object and only differ in their strength.

    Trick to remember the difference : has A -Aggregation and Own - cOmpositoin

    Now let observe the following image

    Analogy:

    Composition: The following picture is image composition i.e. using individual images making one image.

    Aggregation : collection of image in single location

    For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.

    0 讨论(0)
  • 2020-11-22 01:57

    In a very simple sentence:
    Aggregation and Composition are subsets of association.

    • A uses B -> this is an aggregation

    • A needs B -> is composition.

    Read more here.

    0 讨论(0)
  • 2020-11-22 01:59

    I know this question is tagged as C# but the concepts are pretty generic questions like this redirect here. So I am going to provide my point of view here (a bit biased from java point of view where I am more comfortable).

    When we think of Object-oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words the object of one class may use services/methods provided by the object of another class. This kind of relationship is termed as association..

    Aggregation and Composition are subsets of association meaning they are specific cases of association.

    enter image description here

    • In both aggregation and composition object of one class "owns" object of another class.
    • But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
    • So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.

    Confused?

    Composition Example : Consider the example of a Car and an engine that is very specific to that car (meaning it cannot be used in any other car). This type of relationship between Car and SpecificEngine class is called Composition. An object of the Car class cannot exist without an object of SpecificEngine class and object of SpecificEngine has no significance without Car class. To put in simple words Car class solely "owns" the SpecificEngine class.

    Aggregation Example : Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning the Car object owns the Wheel object but we cannot say the Wheel object has no significance without the Car Object. It can very well be used in a Bike, Truck or different Cars Object.

    Summing it up -

    To sum it up association is a very generic term used to represent when a class uses the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.

    More details here. I am the author of http://opensourceforgeeks.blogspot.in and have added a link above to the relevant post for more context.

    0 讨论(0)
  • 2020-11-22 02:00

    Composition (If you remove "whole", “part” is also removed automatically– “Ownership”)

    • Create objects of your existing class inside the new class. This is called composition because the new class is composed of objects of existing classes.

    • Typically use normal member variables.

    • Can use pointer values if the composition class automatically handles allocation/deallocation responsible for creation/destruction of subclasses.

    Composition in C++

    #include <iostream>
    using namespace std;
    /********************** Engine Class ******************/
    class Engine
    {
        int nEngineNumber;
        public:
        Engine(int nEngineNo);
        ~Engine(void);
    };
    Engine::Engine(int nEngineNo)
    {
        cout<<" Engine :: Constructor " <<endl;
    }
    Engine::~Engine(void)
    {
        cout<<" Engine :: Destructor " <<endl;
    }
    /********************** Car Class ******************/
    class Car
    {
        int nCarColorNumber;
        int nCarModelNumber;
        Engine objEngine;
        public:
        Car (int, int,int);
        ~Car(void);
    };
    Car::Car(int nModelNo,int nColorNo, int nEngineNo):
    nCarModelNumber(nModelNo),nCarColorNumber(nColorNo),objEngine(nEngineNo)
    {
        cout<<" Car :: Constructor " <<endl;
    }
    Car::~Car(void)
    {
        cout<<" Car :: Destructor " <<endl;
        Car
        Engine
        Figure 1 : Composition
    }
    /********************** Bus Class ******************/
    class Bus
    {
        int nBusColorNumber;
        int nBusModelNumber;
        Engine* ptrEngine;
        public:
        Bus(int,int,int);
        ~Bus(void);
    };
    Bus::Bus(int nModelNo,int nColorNo, int nEngineNo):
    nBusModelNumber(nModelNo),nBusColorNumber(nColorNo)
    {
        ptrEngine = new Engine(nEngineNo);
        cout<<" Bus :: Constructor " <<endl;
    }
    Bus::~Bus(void)
    {
        cout<<" Bus :: Destructor " <<endl;
        delete ptrEngine;
    }
    /********************** Main Function ******************/
    int main()
    {
        freopen ("InstallationDump.Log", "w", stdout);
        cout<<"--------------- Start Of Program --------------------"<<endl;
        // Composition using simple Engine in a car object
        {
            cout<<"------------- Inside Car Block ------------------"<<endl;
            Car objCar (1, 2,3);
        }
        cout<<"------------- Out of Car Block ------------------"<<endl;
        // Composition using pointer of Engine in a Bus object
        {
            cout<<"------------- Inside Bus Block ------------------"<<endl;
            Bus objBus(11, 22,33);
        }
        cout<<"------------- Out of Bus Block ------------------"<<endl;
        cout<<"--------------- End Of Program --------------------"<<endl;
        fclose (stdout);
    }
    

    Output

    --------------- Start Of Program --------------------
    ------------- Inside Car Block ------------------
    Engine :: Constructor
    Car :: Constructor
    Car :: Destructor
    Engine :: Destructor
    ------------- Out of Car Block ------------------
    ------------- Inside Bus Block ------------------
    Engine :: Constructor
    Bus :: Constructor
    Bus :: Destructor
    Engine :: Destructor
    ------------- Out of Bus Block ------------------
    --------------- End Of Program --------------------
    

    Aggregation (If you remove "whole", “Part” can exist – “ No Ownership”)

    • An aggregation is a specific type of composition where no ownership between the complex object and the subobjects is implied. When an aggregate is destroyed, the subobjects are not destroyed.

    • Typically use pointer variables/reference variable that point to an object that lives outside the scope of the aggregate class

    • Can use reference values that point to an object that lives outside the scope of the aggregate class

    • Not responsible for creating/destroying subclasses

    Aggregation Code in C++

    #include <iostream>
    #include <string>
    using namespace std;
    /********************** Teacher Class ******************/
    class Teacher
    {
        private:
        string m_strName;
        public:
        Teacher(string strName);
        ~Teacher(void);
        string GetName();
    };
    Teacher::Teacher(string strName) : m_strName(strName)
    {
        cout<<" Teacher :: Constructor --- Teacher Name :: "<<m_strName<<endl;
    }
    Teacher::~Teacher(void)
    {
        cout<<" Teacher :: Destructor --- Teacher Name :: "<<m_strName<<endl;
    }
    string Teacher::GetName()
    {
        return m_strName;
    }
    /********************** Department Class ******************/
    class Department
    {
        private:
        Teacher *m_pcTeacher;
        Teacher& m_refTeacher;
        public:
        Department(Teacher *pcTeacher, Teacher& objTeacher);
        ~Department(void);
    };
    Department::Department(Teacher *pcTeacher, Teacher& objTeacher)
    : m_pcTeacher(pcTeacher), m_refTeacher(objTeacher)
    {
        cout<<" Department :: Constructor " <<endl;
    }
    Department::~Department(void)
    {
        cout<<" Department :: Destructor " <<endl;
    }
    /********************** Main Function ******************/
    int main()
    {
        freopen ("InstallationDump.Log", "w", stdout);
        cout<<"--------------- Start Of Program --------------------"<<endl;
        {
            // Create a teacher outside the scope of the Department
            Teacher objTeacher("Reference Teacher");
            Teacher *pTeacher = new Teacher("Pointer Teacher"); // create a teacher
            {
                cout<<"------------- Inside Block ------------------"<<endl;
                // Create a department and use the constructor parameter to pass the teacher to it.
                Department cDept(pTeacher,objTeacher);
                Department
                Teacher
                Figure 2: Aggregation
            } // cDept goes out of scope here and is destroyed
            cout<<"------------- Out of Block ------------------"<<endl;
            // pTeacher still exists here because cDept did not destroy it
            delete pTeacher;
        }
        cout<<"--------------- End Of Program --------------------"<<endl;
        fclose (stdout);
    }
    

    Output

    --------------- Start Of Program --------------------
    Teacher :: Constructor --- Teacher Name :: Reference Teacher
    Teacher :: Constructor --- Teacher Name :: Pointer Teacher
    ------------- Inside Block ------------------
    Department :: Constructor
    Department :: Destructor
    ------------- Out of Block ------------------
    Teacher :: Destructor --- Teacher Name :: Pointer Teacher
    Teacher :: Destructor --- Teacher Name :: Reference Teacher
    --------------- End Of Program --------------------
    
    0 讨论(0)
  • 2020-11-22 02:01

    I'd like to illustrate how the three terms are implemented in Rails. ActiveRecord calls any type of relationship between two models an association. One would not find very often the terms composition and aggregation, when reading documentation or articles, related to ActiveRecord. An association is created by adding one of the association class macros to the body of the class. Some of these macros are belongs_to, has_one, has_many etc..

    If we want to set up a composition or aggregation, we need to add belongs_to to the owned model (also called child) and has_one or has_many to the owning model (also called parent). Wether we set up composition or aggregation depends on the options we pass to the belongs_to call in the child model. Prior to Rails 5, setting up belongs_to without any options created an aggregation, the child could exist without a parent. If we wanted a composition, we needed to explicitly declare this by adding the option required: true:

    class Room < ActiveRecord::Base
      belongs_to :house, required: true
    end
    

    In Rails 5 this was changed. Now, declaring a belongs_to association creates a composition by default, the child cannot exist without a parent. So the above example can be re-written as:

    class Room < ApplicationRecord
      belongs_to :house
    end
    

    If we want to allow the child object to exist without a parent, we need to declare this explicitly via the option optional

    class Product < ApplicationRecord
      belongs_to :category, optional: true
    end
    
    0 讨论(0)
提交回复
热议问题