The Singleton pattern
The Singleton pattern is as the name suggests is a pattern that is used when we want only one of something. And more importantly, that we need to absolutely guarantee we only have one of something. The something I refer to is an instance of a class. Furthermore, the Singleton pattern is also used when we want to allow global access to some of its data or methods. The class can then be used from anywhere within a project and yet is also guaranteeing that all parts/classes of the project that access the class are using the exact same instance.
Part of the Singleton conundrum is simple. To make parts of it available to any other class you simply make the methods public
and static
.
Tip
See Chapter 8: Object-Oriented Programming for a reminder about static
variables.
But how do we guarantee that only one instance can ever be created? We will look at the code next but as a look-ahead what we will do is create a class which has a private
constructor. Remember that a private
...