-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathSingletonPattern2.java
More file actions
106 lines (98 loc) · 2.33 KB
/
Copy pathSingletonPattern2.java
File metadata and controls
106 lines (98 loc) · 2.33 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.so;
/**
* 第2题 单例设计模式
* 设计一个类,只能生成该类的一个实例。
*
* @author qgl
* @date 2019/06/21
*/
public class SingletonPattern2 {}
/**
* 1.饿汉式:线程安全,耗费资源
*/
class HugerSingleton1 {
//该对象的引用不可修改
private static final HugerSingleton1 ourInstance = new HugerSingleton1();
public static HugerSingleton1 getInstance() {
return ourInstance;
}
private HugerSingleton1() {}
}
/**
* 2.饿汉式:在静态代码块实例对象
*/
class HugerSingleton2 {
private static HugerSingleton2 ourInstance;
static {
ourInstance = new HugerSingleton2();
}
public static HugerSingleton2 getInstance() {
return ourInstance;
}
private HugerSingleton2() {}
}
/**
* 3.懒汉式:非线程安全
*/
class Singleton1 {
private static Singleton1 ourInstance;
public static Singleton1 getInstance() {
if (null == ourInstance) {
ourInstance = new Singleton1();
}
return ourInstance;
}
private Singleton1() {}
}
/**
* 4.线程安全的懒汉式:给方法加锁
*/
class Singleton2 {
private static Singleton2 ourInstance;
public synchronized static Singleton2 getInstance() {
if (null == ourInstance) {
ourInstance = new Singleton2();
}
return ourInstance;
}
private Singleton2() {}
}
/**
* 5.线程安全的懒汉式:双重检查锁(同步代码块)
*/
class Singleton3 {
private static Singleton3 ourInstance;
public static Singleton3 getInstance() {
if (null == ourInstance) {
synchronized (Singleton3.class) {
if (null == ourInstance) {
ourInstance = new Singleton3();
}
}
}
return ourInstance;
}
private Singleton3() {}
}
/**
* 6.线程安全的懒汉式:静态内部类(推荐)
*/
class Singleton4 {
private static class SingletonHolder {
private static Singleton4 ourInstance = new Singleton4();
}
public static Singleton4 getInstance() {
return SingletonHolder.ourInstance;
}
private Singleton4() {
}
}
/**
* 7.线程安全的懒汉式:枚举
*/
enum Singleton5 {
INSTANCE;
public void whateverMethod() {
// do something
}
}