Keywords: current

Next: 1.5 Basic Program Design Up: 1.4 The Union and Previous: 1.4.5 Blocks

## 1.4.6 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 ??.

Next: 1.5 Basic Program Design Up: 1.4 The Union and Previous: 1.4.5 Blocks