-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSingletonExample.java
35 lines (28 loc) · 995 Bytes
/
SingletonExample.java
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
package com.javaexperiments;
/**
* Singleton is a design pattern by which you create a singleton class that has only one instance
* at any time
*/
public class SingletonExample {
private static SingletonExample single_instance = null;
public String msg;
// Making the constructor as private
private SingletonExample() {
msg = "Hello World!";
}
/**
* Static method to create instance of Singleton class
*
* @return single object of 'SingletonExample' class
*/
public static SingletonExample getInstance() {
// Ensuring only one instance is created
if (single_instance == null) single_instance = new SingletonExample();
return single_instance;
}
public static void main(String[] args) {
// Instantiating SingletonExample class with variable 'singletonObject'
SingletonExample singletonObject = SingletonExample.getInstance();
System.out.println(singletonObject.msg);
}
}