Skip to content

Commit ed2d4a0

Browse files
author
Liu Yuning
committed
add singleton DP
1 parent 7159798 commit ed2d4a0

3 files changed

Lines changed: 81 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package designpattern.singleton;
2+
3+
/**
4+
* 单例类,使用饿汉式,线程安全(不存在同步问题,但是类被加载即被初始化,特定条件下耗费内存);注释为饱汉式,存在线程不安全的问题
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public class Singleton {
10+
11+
// 饱汉式
12+
// private static Singleton instance;
13+
14+
// 饿汉式
15+
private static final Singleton instance = new Singleton();
16+
17+
private Singleton() {
18+
19+
}
20+
21+
public static Singleton getInstance() {
22+
// 饱汉式
23+
// if (instance == null) {
24+
// instance = new Singleton();
25+
// }
26+
27+
return instance;
28+
}
29+
30+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package designpattern.singleton;
2+
3+
/**
4+
* 单例模式客户端
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public class SingletonClient {
10+
public static void main(String[] args) {
11+
12+
SingletonThreadSafe instance1 = SingletonThreadSafe.getInstance();
13+
SingletonThreadSafe instance2 = SingletonThreadSafe.getInstance();
14+
15+
if (instance1.equals(instance2)) {
16+
System.out.println("同样的实例");
17+
} else {
18+
System.out.println("不同的实例");
19+
}
20+
21+
}
22+
23+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package designpattern.singleton;
2+
3+
/**
4+
* 线程安全的写法,单例模式最优写法
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public class SingletonThreadSafe {
10+
private static volatile SingletonThreadSafe instance;
11+
12+
private SingletonThreadSafe() {
13+
14+
}
15+
16+
public static SingletonThreadSafe getInstance() {
17+
if (instance == null) {
18+
synchronized (SingletonThreadSafe.class) {
19+
if (instance == null) {
20+
instance = new SingletonThreadSafe();
21+
}
22+
}
23+
}
24+
25+
return instance;
26+
}
27+
28+
}

0 commit comments

Comments
 (0)