|Lesson 7||Singleton: consequences|
|Objective||Consider the Effects of using a Singleton.|
Consequences of the Singleton Pattern
Some consequences of the Singleton pattern include controlling access, permitting subclassing, and enhancing flexibility.
The Singleton class can easily control who accesses its single instance and how. The
getInstance() method can keep track of how
many classes have "checked out" the instance. It can queue requests. It can verify the state of the system before
Primarily, this is a consequence of making the instance field non-public and passing all access through the
This consequence is far from unique to the Singleton pattern. Almost all well-designed classes have this characteristic.
The Singleton class can be subclassed. Subclasses can return an object that behaves differently than originally intended.
This allows client applications to be configured at runtime by selecting a different subclass.
An alternative to the Singleton class would be to create a class with only static members .
Since static members have only one value per class, the immediate effect would be similar.
However, pure static members do not lend themselves to subclassing.
Furthermore, it is often easier to work with instance methods and fields when the same object must be used in different objects at the same time.
Singleton Consequences - Quiz