Join Elisabeth Robson for an in-depth discussion in this video Implementing the classic singleton pattern, part of Foundations of Programming: Design Patterns.
- View Offline
To create a singleton class, we create a private static instance variable for the singleton instance and a private constructor that does nothing. The private constructor ensures that no other class can instantiate a new singleton instance. And the private instance variable ensures that to get an instance of the singleton, we must use the getInstance method. The get Instance method is public, and it's a static method, which means that it's class method. So we'll use the class name, Singleton, to call the method.
In the get Instance method, we first check to see if the Singleton instance already exists by checking to see if the field uniqueInstance is null. If it is, then we need to create the Singleton. Again, because the constructor is private, we can only create the Singleton instance from inside the Singleton class like we're doing here. We then return the instance of the Singleton. The next time another object calls getInstance, uniqueInstance will not be null, and so getInstance will return the existing Singleton instance.
This ensures that only one instance of the singleton class will ever exist. Also, notice that we are creating the Singleton only when we actually need it. That is, if no object in your code ever calls the Singleton get instance method. Then the Singleton is never instantiated. This is called lazy instantiation, and it can come in handy if the class is complex and resource intensive, and should only be instantiated if and when it's really needed.
We found it another method to the Singleton, just to show how we can use it once it's created. The getDescription method simply returns a string describing the Singleton. So let's create a Singleton. Our main class is SingletonClient, and all we do here is create a Singleton by calling its getInstance method. And then use the Singleton to get its description. If we call singleton get instance again, we'll get the same instance back. This is just a very simple example of a singleton.
But you can probably see how this could be used to create a more complex class when you want to ensure there's only ever one instance of that class.
- What are design patterns?
- Encapsulating code that varies with the strategy pattern
- Setting behavior dynamically
- Implementing the observer pattern
- Creating chaos with inheritance
- Extending behavior with composition
- Dealing with multithreading and the singleton pattern
- Revising the design for a state machine
- Encapsulating iteration with the collection pattern
- Encapsulating object creation with the factory method pattern