Lecture thumbnail 0:02 / 1:53 We’re now going to take a look at the composite design pattern, which has the peculiar goal of allowing
us to treat individual components and aggregate objects in the same manner.
So what is it all about and why do we need it?
Well, we know that objects typically use other objects, fields or properties or members through either
inheritance, meaning you inherit and then use the base class members, for example, or through composition
and composition actually lets us make compound objects like an object made up of several objects.
So, for example, you can use composition to make a mathematical expression composed of simple expressions
like addition, multiplication, literals, and you can build that into a tree.
Or, for example, if you’re working with a drawing application, you could have a shape that you draw
on the screen, but you can also have a grouping of shapes.
So you select several shapes, you go ahead and you select group in the menu.
And this is something that many drawing applications or applications like PowerPoint, which I’m using
right now, actually support this idea of grouping.
So you can have a grouping of several shapes and that group would consist of several shapes selected
together and then you can drag them together and so on.
So essentially the composite design pattern allows us to treat both single or individual or scalar objects
as well as these groupings, these composite objects in the same manner.
So for example, if you have an object of type foo, but you also have a collection of foo or some class
which inherits from a collection foo, they have certain common APIs which you can then call on one
or the other without knowing in advance whether you’re working with a single element or with the entire
collection.
So the composite design pattern is quite simply a mechanism for treating individual or scalar objects
and compositions of objects in a uniform manner.
Stop Play Play Play Start Play information alert