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.class Empty extends DeptDirectory{ ... static final Empty only = new Empty(); }
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.
Then code outside of class Empty cannot perform the operationclass Empty extends DeptDirectory{ ... private Empty() {} static final Empty only = new Empty(); }
new Empty();