Let’s talk about the moon and the singleton design pattern.

No object-oriented programming language in the world puts restrictions on the creation of many objects(of any class).

Abhijeet Rai
Dev Genius

--

But sometimes it might not be feasible if multiple instances(objects) of any class exist in the program. For example, suppose a class is written to communicate with the hardware. Now imagine what would happen if multiple instances of that class are running around, telling the hardware to do something while another thing is in execution. Object 1 tells to execute task 1, at the same time Object 2 comes with task 2.

Can you imagine how, out of order that will be? The solution in such a scenario is a singleton design pattern. Which allows the existence of only one object of any class. Only one object will be used to communicate with the hardware. Or in another case, only one object will be used to track login activity(logging).

Photo by Photos by Lanty on Unsplash

What would happen if Earth had multiple moons(natural satellites)? It would result in an enormous amount of volcanic activity. Well, that is not feasible(practical) for humankind. So, let’s write a java code such that multiple instances of class NaturalSatellite are not created at any point in the program and show the real-life application of the singleton design pattern.

The first step is to make the constructor private of class(NaturalSatellite), on which we are applying a singleton design pattern. So that we cannot go on creating objects of that class whenever and how many ever we want.

Secondly, we write a factory method ( static NaturalSatellite getSatellite() ). This method returns us an instance of NaturalSatellite.

Thirdly we write a private static variable, that will be used in the static method getSatellite() to check, whether any instance of NaturalSatellite already exists, if it does return the existing instance, if any instance of NaturalSatellite does not exist, then create a new one. Using this approach, we cannot ever create multiple instances of NaturalSatellite

--

--

Hi, I am Abhijeet. I believe everyone has a story to tell. Come, let’s chit- chat. We might end up discussing programming, history, or life. Who knows!