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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
 
class Calculator
{
	private static int count;// static variable
        private static Calculator ref1; //static class type reference variable 
 
	private Calculator()// priavte constructor
	{
		System.out.println(count);
		System.out.println("creating calculator instance");
		count++;
	}
 
 
	void devide(int n1,int n2)
	{
 
		System.out.println("deviding "+n1 +" by "+n2);
		int res=n1/n2;
		System.out.println("result is: "+res);
 
	}
 
	static Calculator getinstance() // static method
	{
 
		if(count==0)
 
		{
 
			ref1=new Calculator();	
 
		}
 
	return ref1;
 
	}
 
}
 
public class Singleton 
{
 
	public static void main(String[] args) 
	{
 
		System.out.println("************************");
 
		Calculator calc1=Calculator.getinstance();
 
		calc1.devide(24, 6);
 
		System.out.println("************************");
	}
}
 
 
output:
************************
creating calculator instance
deviding 24 by 6
result is: 4
************************