This is one of the most famous design patterns regarding interview questions.
Imagine a building with G + 4 floors. Each floor has 2 apartments and a total of 8 apartments in the building. On average, 4 members per apartment you should have a minimum of 32 members using the elevator.
Now consider an office building of 8 floors. There are at least 5 offices on each floor, and the number of employees in each of them is never limited.
In the first scenario, we did not need more than one elevator. In the second scenario, one elevator was simply not enough.
Now that you understand the need for a single lift and the need for multiple lifts. This gives us reason to understand Singleton's design scheme.
DESIGNING SINGLETON DESIGN
Like the elevator in the previous example, the Singleton design pattern is also used to create and use ONLY ONE instance of the object.
Why? Because the application does not require more than one object.
If you saw professional offices, you would notice that one printer is used by all employees on the same floor. All students do not keep the printer at home, they prefer to go and pay in a cyber cafe in their colony and use their printer for their instant requirements.
All this, because the given object MUST here. From a software point of view, an object is โexpensiveโ when it uses a lot of resources to do its job.
So now we have a need for the Singleton design pattern:
1) when the application will not use this object more than several times throughout the life cycle.
2) when the application needs the object often, but the object itself is very expensive to calculate.
SINGLETON SOFTWARE IMPLEMENTATION
The Singleton design pattern states that: Allow only one instance of the class to be created in the entire application and provide a global access point to it
So, the first part relates to the "limiting" design.
From the first days of the object-oriented implementation in Java, we know that constructors are special functions that are called at run-time and can be made private. When the constructor becomes private, any code outside the class cannot create its own object. Therefore, to implement the Singleton design pattern, we will need a "private constructor", and we will create an object inside the class using this constructor.
The second part of our definition is about providing a global handle to this single object. We will do this using a public method.