Noah Subrin's DEV Blog
Technology for Business minds

Iterator and Composite Design Patterns

Print the article

This entry was posted on 11/9/2006 6:23 PM and is filed under Design Patterns.

This week in my SRA-U "Design Patterns in Software Development" class, we discussed the Iterator and Composite Design Patterns.

The Iterator Pattern provides a way to access elements of an aggregate object without exposing its underlying implementation. An aggregate object is another way of saying collection class. In our code scenario we had to develop a menu for a restaurant that had merged a diner with a pancake house. The diner's menu was based on an array. The pancake house's menu was based on an ArrayList. We needed to design a solution that could traverse any collection class. Our solution was based on the Iterator pattern. In the Iterator pattern we create an Iterator interface which defines an interface for traversing elements. The ConcreteIterators implement the Iterator interface and keep track of the current position in the traversal of the collection. The Aggregate defines an interface for creating an Iterator object. The ConcreteAggregate implements the Iterator creation interface to return an instance of the proper ConcreteIterator. From this design we were able to accomodate both collection classes and be able to handle any collection, such as a hash table, that implemented the Iterator.

This solution was fine until we asked the question - what about submenus? We wanted a way to treat menus, submenus, and menu items in the same fashion. For this design scenario we used the Composite pattern. The Composite Pattern allows us to compose objects into tree structures to represent part-whole hierarchies.
The Composite pattern lets clients treat individual objects and compositions of objects uniformly. We can print or traverse menus, submenus, and items using the same structure. The participants in the Composite pattern are the Client, the Component, the Composite, and the leaf. The client uses the Component interface to manipulate the objects in the composition.The Component defines an interface for all objects in the composition – both leaf and composite nodes.The Composite’s role is to define the behavior of the components having children and to store child components. The Composite also implements the Leaf related operations.A leaf defines the behavior for the elements in the composition. It does this by implementing the operations the Composite supports.

My slide deck for this presentation can be downloaded here



 

 

What did you think of this article?




Trackbacks
Trackback specific URL for this entry
  • No trackbacks exist for this entry.
Comments
    • No comments exist for this entry.
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.