Skip to content

Commit 469cb10

Browse files
author
liuyj-m
committed
add
1 parent 80d318b commit 469cb10

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

src/a03_Singleton/Singleton2.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package a03_Singleton;
2+
3+
/**
4+
* 单例模式 - 懒汉式 (性能 换 资源)
5+
*
6+
*/
7+
public class Singleton2 {
8+
9+
/* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
10+
private static Singleton2 instance = null;
11+
12+
/* 私有构造方法,防止被实例化 */
13+
private Singleton2() {
14+
}
15+
16+
/* 静态工程方法,创建实例 */
17+
public synchronized static Singleton2 getInstance() {
18+
if (instance == null) {
19+
instance = new Singleton2();
20+
}
21+
return instance;
22+
}
23+
24+
}

src/a03_Singleton/Singleton3.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package a03_Singleton;
2+
3+
/**
4+
* 单例模式 - 双重检查
5+
*
6+
*/
7+
public class Singleton3 {
8+
9+
/* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
10+
private static volatile Singleton3 instance = null;
11+
12+
/* 私有构造方法,防止被实例化 */
13+
private Singleton3() {
14+
}
15+
16+
/* 静态工程方法,创建实例 */
17+
public static Singleton3 getInstance() {
18+
//double check
19+
if (instance == null) {
20+
synchronized (instance) {
21+
if (instance == null) {
22+
instance = new Singleton3();
23+
}
24+
}
25+
}
26+
return instance;
27+
}
28+
29+
}

0 commit comments

Comments
 (0)