GofPatterns Gofpatterns  





Design Patterns  «Prev  Next»
Lesson 7Singleton: consequences
ObjectiveConsider 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.

Controls access

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 returning.
Primarily, this is a consequence of making the instance field non-public and passing all access through the getInstance() method.
This consequence is far from unique to the Singleton pattern. Almost all well-designed classes have this characteristic.


Permits subclassing

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.

Enhances flexibility

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

Here is a short quiz with respect to the Singleton Design Pattern.
Singleton Consequences - Quiz