next up previous
Next: Basic Program Design Up: The Union and Composite Previous: Blocks

Singleton Pattern

One of the most important uses of static final fields 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();
A private member of a class C is only visible inside class C. We will discuss visibility modifiers in more detail in Section 1.7.7.


Finger exercise 1.6.6.1: Modify your DeptDirectory program to use the singleton pattern to represent the Empty DeptDirectory.


next up previous
Next: Basic Program Design Up: The Union and Composite Previous: Blocks
Corky Cartwright 2004-02-05