loading...

Composite Design Pattern [Structural]

itscoderslife profile image Damodar Shenoy Originally published at itscoderslife.wordpress.com on ・2 min read

This pattern can be used to create recursive tree structures of related objects where any element can be a composition of objects or an individual object. Each element of the structure may be accessed in a uniform manner without having to know whether we use a collection or a leaf object.

  • Clients can ignore the difference between leaf and composed objects, and only use one type or protocol when accessing the elements within the composite structure.
  • All types participating in the composite must implement the same interface. So, here’s a formal definition.
  • With the composite pattern, we can represent part, whole hierarchies of objects.
  • We can access the elements without having to know whether we use a collection or a leaf object.
  • Callers can rely on the same type or protocol to access the elements within the composite structure.

The composite pattern allows related individual objects and collections of objects to be treated uniformly.

Treat individula objects and collection of objects uniformly. Use the same interface to access the elements.

Here is an example from sourcemaking:

Although the example is abstract, arithmetic expressions are Composites. An arithmetic expression consists of an operand, an operator (+ – * /), and another operand. The operand can be a number, or another arithmetic expression. Thus, 2 + 3 and (2 + 3) + (4 * 6) are both valid expressions.

Composite_example1-2x

One more example is of FileManager directory listing. An entry in file system can be a directory or a file. A directory can contain both directories and files. Here we make an file system entry interface and make directory and file class implement. Directory will composite an array of file system entry which can either be dir or a file.

Summary : Leaf and composite objects must implement the same interface so that they can be treated uniformly. With the composite pattern, we can represent part, whole hierarchies of objects. We can access the elements without having to know whether we use a collection or a leaf object. Callers can rely on the same type or protocol to access the elements within the composite structure.

Common failures : one of the problems you may face when implementing the composite pattern is that your design may become overly general.

Posted on by:

itscoderslife profile

Damodar Shenoy

@itscoderslife

Mobile App Developer. Working as iOS developer with Obj-C / Swift. Learning Android development. Full-stack enthusiast. All things tech. Exploring Machine Learning.

Discussion

markdown guide