The Singleton pattern is one of the simplest design patterns around there, so far at least. It’s like the hello world of design patterns with almost everyone using it as the first design pattern example when teaching.
So what is this Singleton pattern?
Well imagine this, you have a printer(without the ability to queue print orders, soon as it gets a command it starts processing it). Only you use it. You print stuff. Everything is fine.Now imagine, you’re not the only one using it. Well okay, it shouldn’t be too much of a problem. As long as you’ll don’t use it at the same time, because then, you will be overwriting the others changes.
This is exactly the problem that the singleton pattern solves, it ensures that only one object, in this case the printer, can exist at any given time.
This is especially useful when it comes to databases, where you don’t want multiple methods trying to read/write from the database at the same time as this can lead to data corruption pretty fast.
Some situations where you might implement singleton include, but are not limited to, database connections, hardware, application logging, and so on.
However, beware, singleton is not always the best solution to a problem. There are some cases in which it is considered to be an anti-Pattern when used in situations where it will not be beneficial. One examples is a multi threaded application. The singleton limits access to only one thread at a time
Here is a high level overview of singleton works:
And here is the class diagram:
So basically what happens is, the singleton class has a private, static object of its OWN TYPE. How this is accessed is through the static getInstance() method, which checks to see if the instance is null, if it is it instantiated the object and returns that object. Otherwise what happens is it calls the private constructor to instantiate itself, which is only accessible to itself due to the private accessibility, and then returns the object.
My next post will have an example of how this is implemented when connecting to a database so stay tuned 🙂
Feel free to comment and ask any questions!