Design Pattern Download: The Composite Pattern
The Composite pattern is a Structural Pattern used in software engineering when you have a tree like structure you want to model like when you have a root object with many children and each of those children have children.
We want to create a button to tell people went to work, when an Engineer’s button is pressed, only they work. When a Manager’s button is pressed, all the Engineers that work for them start to work. And when a Director’s button is pressed, all of the Engineers of all of the Managers under them start to work. We can achieve this by storing a list of Engineers in the Manager object (so the Manager is composed of Engineers) and likewise for Directors and Managers.
When to use the Composite?
- When we want to represent a tree like hierarchy in code
- When the functionality of one node in the tree depends on their parent or children to do some function
What is the Composite Pattern composed of?
- Hierarchal classes ( each class will have a list of the class type on layer below it)
Here we just create a simple interface which all our employees will implement.
The Hierarchal Classes
The upper level classes (Director and Manager) have lists of the level immediately below it and notice how when they are told to work, they delegate and call their children’s work function. This creates a fanning out until we reach the leaf node Engineer who does not have any layer below them and so they simply say “Engineer is doing work”.