composite - Harsh4999/Design-Patterns GitHub Wiki

Composite

Use

  • When we have a part-whole relationaship or hierarchy of objects and we want to be abe to treat all objects in this hierarchy uniformly
  • Allows us to treat in same way when they are in a tree structure
  • Its not simple composition

UML

  • Component = abstract base class which defines behaviour common to all classes it adds method which allows the access to children in base class
  • Leaf = Class which represnts the leaf node implementation for operations and functionality which is required by the client
  • Composite = Stores child components

Implementation

  • Component must declare all methods that are applicable to both leaf and composite
  • We have to choose who defines the children management operations component or composite.
  • We implement the composite an operation invoked on composite is propogated to all its children
  • In leaf nodes we have to handle the non-applicable operations like add/remove a child if they are defined in component
  • Decision needs to be made about where child management operations are deinfined. Defining them on component provides transparency but leaf nodes are forced to implement those methods
  • Eg: UIViewRoot