Implementation Issues
Variant 1:
Subclassing not possible.
-
(1) The INSTANCE constant is set to the
instance of the class.
Fields declared final are initialized
once and can never be changed.
In Java, "Final fields also allow programmers
to implement thread-safe immutable objects
without synchronization."
[JLS12
,
17.5 Final Field Semantics]
-
(2) The constructor of the class is
hidden (declared
private).
This ensures that the class can neither
be instantiated (from outside the class) nor
subclassed (subclasses need/call the constructor of their
parent class).
-
(3) The public static
getInstance()
operation returns the
INSTANCE constant.
Clients can access the sole instance easily
by calling
Singleton.getInstance().
-
See also Flyweight and State / Sample Code.
Variant 2:
Subclassing possible.
-
(1) The
instance field holds the
instance of a subclass.
-
(2) Singleton's default constructor is used.
Because the class is abstract,
it can't be instantiated.
-
(3) The public static final
getInstance() operation
must decide which subclass to instantiate.
This can be done in different ways:
according to user input, system environment,
configuration file, etc.
Note that operations declared final
can't be redefined by subclasses.
-
See also Abstract Factory / Sample Code / Example 3 /
Creating families of objects.