next up previous
Next: 1.10.2 Other Uses of Up: 1.10 Static Members of Previous: 1.10 Static Members of

1.10.1 Singleton Pattern

One important use of static 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.


Finger Exercise how could you ensure that other classes cannot call the zero-ary constructor for Empty?


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();



Corky Cartwright
2000-01-07