# Composite pattern

Composite is a structural design patterns.

Via wikipedia:

The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

In short, we combine multiple objects into one, without losing access to a specific object

Component – An interface that defines the behavior for a particular object or group of objects

Leaf – Single object that has no descendants, implements the interface Component

Composite -Group of objects, consiting of leaves, implements the interface Component

# Example

Let’s see how it works on a simple example of how to solve the equation ((((2+5)-1)*4)/3).

In a first step, we write interface.

Now we implement leaf class that represents a single number / result.

Now we implement classes(composite) that represent arithmetic operations like addition, multiplication, divide and subtraction.

And the same will be in other classes with arithmetic operations only difference is a method of Calculate and Show

Divide:

Multiplication:

Subtraction:

Now let’s apply our pattern for the calculation of expression ((((2 + 5) -1) * 4) / 3)

As u see in this approach we combine multiple objects into a single object and we perform methods on it. We can also refer to any of these objects.

# Summary

Compsite patter we can apply where we got a simillar objects and we can merge them into one, without losing access to a specific object eg. take total cost from one objects which is the sum of all objects(these objects can have different methods to count their own costs) but we still have access to the cost of each object.
In this way we can manipulate large amounts of objects instead refer to them individually, we can call a method on the entire group.

Link to the project : here

View all posts by Paweł Filipek →

### 4 Comments on “Composite pattern”

1. Mateusz says:

Nice post, but you should change description of operations, because you made a little mistake there 😉

1. Paweł Filipek says:

What mistake? 😉

1. Martin says:

Subtraction: is twice in description

1. Paweł Filipek says:

Corrected. Thank You 😉