next up previous
Next: 1.5.3.1 Type Predicates and Up: 1.5 Basic Program Design Previous: 1.5.2 An Extended Example:

1.5.3 Singleton Pattern

One of the most important uses of static final fields (constants) is storing the canonical instance of a class that only needs a single instance. For example, the Empty subclass of DeptDirectory only needs one instance because the class has no (dynamic) fields.

class Empty extends DeptDirectory{
  ...
  static final Empty ONLY = new Empty();
}
Instead of allocating new instances of Empty, code can simply refer to the canonical instance Empty.ONLY. The final attribute stipulates that the variable ONLY cannot be modified. This code pattern is called the singleton pattern because it constructs a single instance of the class.

The implementation of the singleton pattern shown above suffers from an annoying defect: the class definition for Empty does not prevent code in another class from creating additional instances of the Empty class. We can solve this problem by making the constructor for Empty private.

class Empty extends DeptDirectory{
  ...
  private Empty() {}	
  static final Empty ONLY = new Empty();
}
Then code outside of class Empty cannot perform the operation
new Empty();


Finger exercise: Load your saved program DeptDirectory.java into the DrJava Definitions pane. Convert it to use the singleton pattern.



Subsections
next up previous
Next: 1.5.3.1 Type Predicates and Up: 1.5 Basic Program Design Previous: 1.5.2 An Extended Example:
Corky Cartwright 2003-07-07