The Singleton Pattern is used to make sure only one object of a particular class is ever created. This can be useful when when exactly one object is needed to coordinate actions across a system; perhaps for efficiency where creating lots of identical objects would be wasteful, perhaps because a particular algorithm needing a single point of control is required or perhaps when an object is used to interact with a non-shareable resource.
Suppose we wish to create a class for collecting votes. Because getting the right number of votes may be very important, we decide to use the singleton pattern. There will only ever be one
VoteCollector object, so it makes it easier for us to reason about that objects creation and use.
Some points of interest about this code:
- it has a private constructor, so no
VoteCollectorobjects can be created in our system (except for the
INSTANCEis also private, so it can't be changed once set
- we haven't made the updating of votes thread-safe at this point (it doesn't add to this example)
- the vote collector instance is not lazyily created (if we never reference the class, the instance won't be created; however, as soon as we reference the class, the instance will be created even if not needed initially)
We can use this singleton class in some script code as follows:
Here we used the instance 3 times. The second usage was even in a different thread (but don't try this in a scenario with a new class loader).
Running this script yields: