Rice University - Comp 212 - Intermediate Programming

Fall 2002

Lecture #06 - Singleton and Composite Design Patterns

0. Recall

Here again is the UML diagram depicting the design of our immutable recursive list structure.  

The above design contains two common "design patterns": the singleton pattern and the composite pattern.

Design patterns are tried-and-true design solutions to recurring problems in software construction.  Design patterns provide ways to structure software components into systems that are flexible, extensible, and have a high degree of reusability.  They also form a pattern language which is used to communicate software design.

Design patterns are often misconstrued as applicable only to programming in the large.  In reality, they can be applied to solving problems in programming in the small such as implementing data structures, such the list structure shown in the above.

1. Singleton Pattern

The EmptyList class may be implemented with the singleton pattern to model the fact that there is a unique empty list.

Click here to see the code.

2. Composite Pattern

An NEList object "has a" an element, called rest, whose structure is isomorphic to the enclosing NEList object itself..  NEList is said to be a composite.  Its structure is recursively constructed and terminates with the "base case", the EmptyList.   The above taxonomy is an example of what is called the composite design pattern.  The composite pattern is a structural pattern that prescribes how to build a container object that is composed of other objects whose structure is isomorphic to that of the container itself.  In this pattern, the container is called a composite.  The composite pattern also prescribes a coding pattern for the container's methods: when a container is called to perform an operation, it traverses through its list of composed objects and call on them to perform the same operation.  It allows the client to treat the container and what it contains uniformly by making use of polymorphism.  The following UML diagram illustrates the general composite pattern.

composite.gif (7317 bytes)

 

Example: 

For the list structure, the methods getLength() and  getMinimum() illustrate the above coding pattern.  Click here to see the code.

// Need to discuss "wrapper" classes, such as Integer, and type-casting in code example.

D. X. Nguyen, last revised 01/28/02
Dung X. Nguyen - Copyright 2002 - All rights reserved