Editorial / Best Answer
hi_goura
Singleton pattern is a design pattern by which we cannot create more than one instance of the class. For a fresh request to get an instance, a new instance will be returned. And further requests will return you the referenceto the earlier one. There is no keyword singleton to make your class as "Singleton Class". You have to design your class accordingly. First of all make the default constructor private and don't give any other constructor to restrict creation of multiple instances from outside of your class. Have a public static method that returns you the reference to the same class (this is called Factory method). Have a class-level (static) private variable whose data-type is same class. Inside the static method, check if the static variable is null then create a new object, assign that to the static variable and return it. If that is not-null, that means this is not the first request, return the same static variable. Now If someone wants an instance of your class, (s)he must call YourClass.staticMethod(). No other option. Thanks-Gourahari
What is singleton pattern ??
Editorial / Best Answer
hi_gouraProfile Answers by hi_goura Questions by hi_goura
Singleton pattern is a design pattern by which we cannot create more than one instance of the class. For a fresh request to get an instance, a new instance will be returned. And further requests will return you the referenceto the earlier one. There is no keyword singleton to make your class as "Singleton Class". You have to design your class accordingly. First of all make the default constructor private and don't give any other constructor to restrict creation of multiple instances from outside of your class. Have a public static method that returns you the reference to the same class (this is called Factory method). Have a class-level (static) private variable whose data-type is same class. Inside the static method, check if the static variable is null then create a new object, assign that to the static variable and return it. If that is not-null, that means this is not the first request, return the same static variable. Now If someone wants an instance of your class, (s)he must call YourClass.staticMethod(). No other option. Thanks-Gourahari
Related Answered Questions
Related Open Questions