Singleton class

Singleton class

  • Singleton class design pattern.
    1. Make constructor private– Restricting object creation
  • 2. Static method– To get instance method
  •  Singleton class is a design pattern which is used to design the class
    such a way that class produce only one instance only given point of time.
  •  We can not create more than one instance of singleton class.
  • In singleton class design
    — Private constructor
    — Public static method which is responsible to return instance of its own class
    —The static method should have necessary logic to create only one instance.
Java program to implement singleton design pattern

[pastacode lang=”java” manual=”class%20Calculator%0A%7B%0A%09private%20static%20int%20count%3B%20%20%2F%2F%20static%20variable%0A%20%20%20%20%20%20%20%20private%20static%20Calculator%20ref1%3B%20%20%20%2F%2Fstatic%20class%20type%20reference%20variable%20%20%20%20%0A%09private%20Calculator()%20%20%20%20%2F%2F%20priavte%20constructor%0A%09%7B%0A%09%09System.out.println(count)%3B%0A%09%09System.out.println(%22creating%20calculator%20instance%22)%3B%0A%09%09count%2B%2B%3B%0A%09%7D%0A%09%0A%09void%20devide(int%20n1%2Cint%20n2)%0A%09%7B%09%0A%09%09System.out.println(%22deviding%20%22%2Bn1%20%2B%22%20by%20%22%2Bn2)%3B%0A%09%09int%20res%3Dn1%2Fn2%3B%0A%09%09System.out.println(%22result%20is%3A%20%22%2Bres)%3B%09%0A%09%7D%0A%09static%20Calculator%20getinstance()%20%20%20%2F%2F%20static%20method%0A%09%7B%0A%09%09if(count%3D%3D0)%0A%09%09%7B%0A%09%09%09ref1%3Dnew%20Calculator()%3B%09%0A%09%09%7D%0A%09return%20ref1%3B%0A%09%7D%0A%7D%0Apublic%20class%20Singleton%20%0A%7B%0A%09public%20static%20void%20main(String%5B%5D%20args)%20%0A%09%7B%0A%09%09%09System.out.println(%22************************%22)%3B%09%0A%09%09Calculator%20calc1%3DCalculator.getinstance()%3B%0A%09%0A%09%09calc1.devide(24%2C%206)%3B%0A%09%09%09System.out.println(%22************************%22)%3B%0A%09%7D%0A%7D%0A%0A” message=”” highlight=”” provider=”manual”/]

output:
************************
creating calculator instance
deviding 24 by 6
result is: 4
************************

Leave a Reply