link: Object Oriented Programming , Relations Between Objects
Composition relationships
Content
Composition is a stringent form of aggregation in object-oriented programming that defines a “part-whole” relationship where parts cannot exist independently of the whole. This type of relationship is crucial for ensuring that objects are well-integrated within a system, enforcing encapsulation and enhancing the system’s robustness.
Composition is a specific kind of aggregation known for its strictness in part-whole relationships:
Important
Composition ensures that when the container (whole) is destroyed, its contents (parts) are also destroyed. This relationship is ideal for representing natural part-whole hierarchies in an application, such as graphical user interfaces or management systems where components must not exist without the whole.
Example
In this C# example:
- The
Car
class is composed of anEngine
. TheCar
owns theEngine
and controls its lifecycle. - The
Engine
cannot exist independently of theCar
, demonstrating a composition relationship. - The methods
Start
andStop
inCar
delegate toEngine
, encapsulating its functionality within theCar
.
References
Favor Composition Over Inheritance - design principle https://refactoring.guru/design-patterns