In this article, we gonna work with one of the structural patterns to solve a specific problem.
Pattern: Composite
The composite pattern is a structural pattern that groups a set of objects into a tree structure so they may be manipulated as though they were one object.
illustration
In the above image, we have a group of teams that forms a unicorn team. each team can contain nested teams like we shown in the backend and mobile team. All team in the hierarchy shares a common interface countable
regardless of whether it's a unicorn or nested. So each team is responsible for conforming to the protocol requirements to create a tree-like behavior.
Implementation
In our example, we gonna calculate the total headcount which the unicorn team operates with. In this scenario, unicornTeam as our composite and others are individual respectively.
Step 1: Protocol Interface
Abstractions that provide a common interface countable
for collections and individual Teams. All elements in the tree must be derived from a component protocol.
Step 2: Teams (Single Object):
Previously referred to as an “individual Team”, Primitives are simply components in the tree that do not contain child components.
Step 3: Unicorn Team (Composite)
As previously referred to as a “collection object”. Composites are objects that hold an array of teams. While Composite and Primitive objects share the same interface countable
, composites contain additional methods to manage their children.
Usage:
/* Creating TeamUnicorn with Composite */
let unicorn = TeamUnicorn()
unicorn.add(BackendTeam())
unicorn.add(FrontEndTeam())
unicorn.add(MobileTeam())
print(unicorn.getHeadCount())
Here is what we did step by step:
Step 1: Created countable
interface for the team communication.
Step 2: Constructed several teams in the creation of unicornTeam, each of which confirmed to the countable
protocol.
Step 3: Create a simple tree hierarchy: Instantiate unicornTeam which contains Backend, Frontend, and MobileTeam.
Usage: Reading the unicorn team count, which internally initiates a recursion on its nested teams to calculate the total count.
Conclusion:
we have done with calculation the total headcount of a team with the use of a composite design pattern. A design pattern is a powerful tool in solving a specific problem. Understanding what pattern has to be used for which problem is the key here.
“Be the senior engineer you needed as a junior.” — Someone
Thank you for reading the post, leave a comment or a pattern which you are using to solve the common pitfalls✌️.