According to my thoughts, we should create the Singleton class when we use the same state of the object in the application. In this case, we want the user to be limited from creating a new instance each time so that they cannot support multiple states. Agreed. But the same behavior can be achieved by declaring instance variables as static. It seems to me that it will also serve the same purpose, whether it be a class cacheobjectcontainer, loggeror Classloader.
Please help me understand the concept above, where a static instance variable will not solve the target and the class must be declared Singleton?
Edited Part
Ok, let me bring you even more clarity. The doll of a single class is to save only one instance of a singleton class via jvm. Agreed. But I'm trying to think about the reasons why we want to keep only one instance. Two reasons are possible:
1) An object can be expensive to create. Therefore, we just want to keep only one instance. Consistent in this scenario, declaring instance variables as static does not solve any goals.
2) We want to use the same state of the object in the application. I thought this was the main purpose of declaring a class as singleton. But this can be achieved simply by declaring instance variables as static.
But it seems that 1 is the main reason for marking up any class as static, and not argument 2, because it can also be achieved using a static variable.
Is it correct?
source
share