Singleton Design Pattern
This design pattern is one instance oriented design pattern and the easiest and the simplest form other 23 design patterns. This pattern allows only one instance and we can't use this pattern unless we need to create only one instance. This design pattern falls into the Creational design patterns category.
This pattern actually allows one instance per container and as an example single instance of a class per a JVM which provides access globally. As another example, let’s think of a Database connection or a socket, when we create a single instance we don't need to recreate instances again and again so using this design pattern we can achieve that simply. But the dark side of this design pattern is if we use this without a good understanding we might get into trouble when performing unit testing since there are no instance variables or any other references to create. and another important thing is we should not take any arguments when creating an instance or else if in need we have to stick with another design pattern (Factory Design Patterns)to keep its form clean.
To keep the pattern clean programmers use some techniques like 1. Creating a constructor private in order to make sure that the singleton class doesn't get instantiated by other classes, 2. Creating static variables for instance which don't take any arguments and 3. Creating only static methods to allow point access globally to the singleton object.
there are two other approaches named “Early initialization” and “Lazy initialization”. In the Early initialization method, it creates instances at the load time and in the Lazy initialization method, it creates instances based on the requirement. The “Synchronized ” keyword is used to make a thread-safe singleton approach called “Double checking Singleton”.
Get Kalana Ravishan Uduwarage’s stories in your inbox
Join Medium for free to get updates from this writer.
Let's take a look at the code example :
there is a company that performs vehicle inspections and customers have to plug their scanner port into the car and a mechanic scans and print a report to the customers. there should only be one inspection handler to handle inspection sessions and two customers can’t get the inspection done at the same time.
Did you notice that even though we created two instances it returned us the same instance despite creating and returning a new instance. And also to keep the thread-safe and clean getInspectionManager method in InspectionManager class and the “double-checking singleton” method is created and they prevent multiple instances and multiple thread instances.







