It is said that composite pattern allows you to compose objects into tree structures to represent part-whole hierachies.It is also said that composite pattern lets clients treat individual objects and composition of objects uniformly. I just need an explanation of what it means to treat individual objects and composition of objects uniformly.
3 Answers
The composite pattern is a partitioning design pattern.
The composite pattern describes that a group of objects
are 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.
Composite can be used when clients should ignore the difference between compositions
of objects
and individual objects
. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.
It lets you treat a group of objects a single entity.
The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object ...
Wikipedia describes an example very well with diagrams and example code that would be too much to duplicate here.
I'll try to make you understand with an example: Consider we have an organization which like any other have employees and Managers. Off-course the managers can have multiple employees under them. Now if we try to design application using composite pattern the managers will be composites which will have list of employees under them. The answer to your question is - Though Mangers are composites they need to be treated as employees as well since they have common behavior, isn't it? Hope this helps.