Composition and Aggregation

Learn about composition and aggregation with some real-world and computer-oriented examples.

So far, we have learned to design systems as a group of interacting objects, where each interaction involves viewing objects at an appropriate level of abstraction. But we don’t yet know how to create these levels of abstraction. Since most design patterns rely on two basic object-oriented principles known as composition and inheritance. Composition is simpler, so let’s start with that first.

Composition

Composition is the act of collecting several objects together to create a new one. Composition is usually a good choice when one object is part of another object. We’ve already seen a first hint of composition when talking about cars. A fossil-fueled car is composed of an engine, transmission, starter, headlights, and windshield, among numerous other parts. The engine, in turn, is composed of pistons, a crank shaft, and valves. In this example, composition is a good way to provide levels of abstraction. The car object can provide the interface required by a driver, while also giving access to its component parts, which offers the deeper level of abstraction suitable for a mechanic. Those component parts can, of course, be further decomposed into details if the mechanic needs more information to diagnose a problem or tune the engine.

Get hands-on with 1200+ tech skills courses.