-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonTest.java
More file actions
54 lines (39 loc) · 1.13 KB
/
SingletonTest.java
File metadata and controls
54 lines (39 loc) · 1.13 KB
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
/*
A Creational Pattern.
Ensure a class has only one instance and provide a global point of access to it.
*/
public class SingletonTest {
public static void main(String[] args){
System.out.println("-------------- SINGLETON ---------------");
Singleton s1 = Singleton.getInstance();
System.out.println("s1: "+s1.getName());
Singleton s2 = Singleton.getInstance();
System.out.println("s2: "+s2.getName());
if(s1 == s2){
System.out.println("s1 and s2 are same instances... changing String of s2 to 'Partha'");
}
s2.setName("Partha");
System.out.println("s2: "+s2.getName());
System.out.println("s1: "+s1.getName());
}
}
//Singleton
class Singleton {
private static Singleton myInstance = null;
private String name = null;
private Singleton(String str) {
name = str;
}
public static Singleton getInstance() {
if (myInstance == null){
myInstance = new Singleton("InitialSingletonString");
}
return myInstance;
}
public String getName(){
return name;
}
public void setName(String str){
name = str;
}
}