Composite

From CSSEMediaWiki
Revision as of 00:57, 8 October 2008 by Yugan Yugaraja (Talk | contribs)
Jump to: navigation, search
Composite pattern

The Composite pattern is useful whenever one has a class which may contain instances of itself. Common computer science examples are nodes in a tree structure, or shapes in a graphical model. More concrete physical world examples include regions (which can potentially contain many smaller regions), schools of fish (where those fish may swim, eat, etc in a collective fashion), and divisions/teams in a workplace.

The key feature of this pattern is a subclass which both extends the superclass, and contains (though an aggregation or composition relationship) a number of instances of the superclass.

The advantage gained from this structure is that we can transparently use a Composite Instance just as with a Primitive instance. shape.draw(), for example could draw any shape, from a primitive to a highly complex diagram or model.


Contents

Features

Classes

  • Interface (Abstract class) that represents Component.
  • Concrete Composite class that implements Component.
  • Concrete leaf class that implements Component.
  • Client class.

Attribute

  • Composite maintains a collection of Components. E.g, Collection<Component>

Methods

  • Component has abstract methods to add and remove an Component to and from.
  • Composite has concrete method to add an instance of Component that shared by Composites and leaves on the collection.
  • Composite has concrete method to remove an instance of Component that shared by Composites and leaves from the collection.

Relationships

  • Composite contains both Composite and leaf as Component.
  • All Composites and leaves are seen as Component by Client.

Recognising the pattern

Classes: Composite, Component, multiple Leaves

  • Inheritance hierarchy that has a Component interface
  • Component interface has declarations for add() and remove() methods for adding/removing Components.
  • Composite class has private collection of Components.

See also

Personal tools