The Singleton design pattern solves problems like:
How can be ensured that a class has only one instance?
How can the sole instance of a class
be accessed globally?
See Applicability section for all problems Singleton can solve.
See Solution section for how Singleton solves the problems.
-
The standard way is to
call the public constructor of a class
(
new Class1()) each time a new object is needed.
-
That's the kind of approach to avoid
if we want to ensure that a class can be instantiated
only once (has only one instance).
-
For example, system objects that hold global data
(like database,
file system, printer spooler, or registry).
[BGI]
It must be ensured that such objects are instantiated only
once within a system and that their sole instance
can be accessed easily from all parts of the system.
-
For example, avoiding creating large numbers of unnecessary objects.
It should be possible to avoid
creating unnecessary (duplicate, functionally
equivalent) objects over and over again
(to avoid excessive memory usage
and system performance problems).
"It is often appropriate to reuse a single object
instead of creating a new
functionally equivalent object each time it is needed."
[JB08, p20]
Background Information
-
Global data should be kept to a minimum
(needed primarily by system objects).
In the object-oriented approach,
"there is little or no global data."
[GB07, p36]
Instead, data should be stored (encapsulated) in those objects
that primarily work on it
and passed to other objects if necessary.
-
A Registry is
"A well-known object that other objects can use to find
common objects and services."
Registry (480)
[MF03 ]