From the course: C++ Design Patterns: Structural
Overview - C++ Tutorial
From the course: C++ Design Patterns: Structural
Overview
- [Instructor] The composite design pattern is a structural design pattern that allows us to compose objects into tree-like structures to represent whole-part hierarchies. The pattern provides a unified interface for both individual objects and compositions of objects which makes it easier to treat them uniformly. The composite pattern is useful when we have a complex object hierarchy that consists of multiple levels of objects. The pattern defines two types of objects, composite and leaf objects. The composite objects are containers that can contain other composite and leaf objects. The leaf objects are the basic building blocks that cannot contain other objects. A good example of the composite design pattern is the filesystem. The filesystem is composed of folders and files. The folder represents a composite object that can contain other folders, the composites and files which are the leaf objects. One of the primary benefits of the composite pattern is that it makes it easier to treat composite and leaf objects uniformly. This means that we can iterate over a composite object and perform operations on all its child objects, regardless of whether they are composite or leaf objects. This is particularly useful when we want to apply the same operations to all objects in a hierarchy. Say that we want to find out how much space a folder uses on the disc. One way to do this is to iterate over all the files within that folder and add up the sizes of each file. If the folder contains other folders, we need to iterate over them and add up the sizes of all their files as well. And if those subfolders have other subfolders, we need to iterate over those as well. During this process, we need to know which objects are folders and which are files. Thus, our code has to check for the object type at each level of the hierarchy. The composite design pattern simplifies this process by allowing us to treat both composite and leaf objects uniformly. We start by defining a common interface for the folder and file classes. This interface should define operations that can be applied to both objects such as size. We then implement the size operation for each type. In the case of file objects, size returns the size of the file. For folder objects size iterates over all its child objects, which can be subfolders or files, calls their size methods, and sums up the results. The process continues until all the subfolders and their files have been processed. Using the composite design pattern, we can now easily calculate the size of a folder and all its subfolders in a uniform way. Since we don't need type checks to determine which objects are folders and which ones are files, our code becomes simpler and more efficient. In the following videos, we'll explore the composite pattern in detail and see how to implement it using C++.