Join Elisabeth Robson for an in-depth discussion in this video What is the singleton pattern?, part of Foundations of Programming: Design Patterns.
In this chapter, we're going to explore the Singleton pattern. Now the Singleton pattern maybe the most well known pattern out there. At first glance, it's deceptively simple but as you'll see, there's a lot of thinking that goes into the correct implementation of the pattern. But before we get to all that, let's take a look at the pattern definition. The Singleton Pattern is a pattern that ensures that there is only ever one single instance of a class. And it provides a global way to get to that instance. Let's break that down. First a Singleton is an instance of a class and by this definition reading closely, that class is making sure that only one instance is ever created.
So conversely, The class is going to prevent any other object from instantiating another instance of the class. That's pretty interesting, if you think about it. And you might think about how you could implement such a thing. Also, this class is responsible for giving us a global access point to that one object. Okay, enough definitions, let's dig into this a little bit. We'll begin with the first obvious question, which is why would you need such a thing? Well, think about implementing systems like connection pools and threads, logging facilities, preferences and registry objects, different types of device drivers, printers, graphics drivers, even UI dialog or modal controls.
There are many resources for which you only need one object. And in fact, if you had more than one, you'd end up with inconsistent or incomplete results or you might even cause an application or system to crash. So, a single object is a necessary and important thing, and in some cases, the reliability of our software might depend on it. Now the second question is, wouldn't it be easy just to create one instance of a class and keep reusing that instance? Well sure, but after going through the definition of the Singleton pattern, it might be clear that there's more to the story, because the pattern prevents any other object from creating a new instance, and there's nothing about this object instantiation that we have on the screen that can ensure that.
In the next chapter, we're going to look at how we might use Java classes to ensure this behavior.
- 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