Singleton classes in java(easy)

in java •  3 years ago 

Singleton classes

Singleton

  • For any java class if we are allowed to create only one object then it is called singleton class.
  • Runtime, BusinessDelegate, ServiceLoactor, etc.

Advantages

  • If several people have same requirement then it is not recommended to create a separate object for every requirement.
  • We have to create one object and we can reuse same object for every similar requirement so that performance and memory utilisation will be improved.
  • This is the central idea of singleton classes.

How to create our own single classes

  • We can create our own singleton classes, for this we have to use private constructor and private static variable and public factory method.
    • Approach 1

public class SingletonDemo.png

- Runtime class is internally implemented by using this approach.

- Approach 2 (Recommended approach)

public class SingletonDemo.png

  • At any point of time for SingletonDemo class we can create only one object hence SingletonDemo class is a singleton class.

Another concept

  • Suppose class is not final but we are not allowed to create child classes, how it is possible?
  • Simple, declare every constructor as private.
  • By using private constructors we can restrict child class creation
  • Example
    • class P {
    • private P() {}
    • }
  • For the above implementation of class P, it is impossible to create child class.
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!