Conteúdo do Curso
C++ OOP
C++ OOP
Segmentation and Aggregation
When you are creating software that is maintainable and flexible, there is a lot to things to consider in process, especially in object-oriented programming. Composition and aggregation are fundamental concepts that enable the creation of complex systems from simpler components and are parts of encapsulation paradigm.
Composition
Composition is a design technique where a class contains objects of other classes as member variables. These members are vital components of the containing class and have a strong ownership relationship. When the containing object is destroyed, its composed parts are also destroyed. For example:
Car
Engine
#include "Engine.h" class Car { public: void Start() { engine.Start(); // Start the engine std::cout << "Car started" << std::endl; } private: Engine engine; // Engine object composition };
The Car class composes an Engine object. When a Car object is created, it automatically creates an Engine instance as a part of its composition.
Aggregation
Aggregation is another form of object composition where a class contains object of other classes, but the contained instances have a weaker relationship compared to composition. In aggregation, the contained member classes can exist independently and may be shared among multiple classes.
Car
Engine
#include "Engine.h" class Car { public: Car(Engine* engine) : engine(engine) {} void Start() { engine->Start(); // Start the engine std::cout << "Car started" << std::endl; } private: Engine* engine; // Engine object aggregation };
In this example, the Car class aggregates an Engine object using a pointer. The Car class does not own the Engine object; it merely holds a reference to it. This allows the Engine instance to exist independently of the Car object and be shared among multiple instances if necessary.
Choosing Between Composition and Aggregation
When designing software systems, it's essential to carefully consider whether to use composition or aggregation based on the relationships between classes and objects.
Containing class must take ownership of contained objects | ||
Contained objects are integral parts of the containing class | ||
Containing class merely references the contained objects | ||
Contained objects can exist independently or be shared among multiple instances |
In the context of a Car and its Engine classes, using composition would be more appropriate. Each car typically has its own engine, and the engine is an integral part of the car itself. Additionally, it prevents the Engine from being shared or reused across multiple car objects, which is also makes sense.
Obrigado pelo seu feedback!