Skip to content

Commit 88c2733

Browse files
committed
add singleton in gof example
1 parent 7293d78 commit 88c2733

File tree

3 files changed

+80
-1
lines changed

3 files changed

+80
-1
lines changed

GOF/gof-example/src/main/java/com/ipipman/gof/example/singleton/GOF-Singleton单例模式.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,49 @@
3030

3131
不过,这样实现方式不支持延迟加载,初始化时可能会耗性能;
3232

33+
```java
34+
public class IdGenerator1 {
35+
private AtomicLong id = new AtomicLong(0);
36+
private static final IdGenerator1 instance = new IdGenerator1();
37+
private IdGenerator1() {
38+
}
39+
public static IdGenerator1 getInstance() {
40+
return instance;
41+
}
42+
public Long getId(){
43+
return id.incrementAndGet();
44+
}
45+
}
46+
```
47+
48+
49+
50+
#### 2. 懒汉试
51+
52+
有饿汉式就有懒汉式;
53+
54+
懒汉式对于饿汉式的优势在于它支持延迟加载,不影响初始化性能;
55+
56+
不过懒汉试缺点也很明显,我们给 getInstance() 加了一个 synchronized 锁,导致这个方法并发度很低,性能非常差;
57+
58+
```java
59+
public class IdGenerator2 {
60+
private AtomicLong id = new AtomicLong(0);
61+
private static IdGenerator2 instance;
62+
private IdGenerator2() {
63+
}
64+
public static synchronized IdGenerator2 getInstance() {
65+
if (instance == null) {
66+
instance = new IdGenerator2();
67+
}
68+
return instance;
69+
}
70+
public Long getId() {
71+
return id.incrementAndGet();
72+
}
73+
}
74+
```
75+
3376

3477

3578

GOF/gof-example/src/main/java/com/ipipman/gof/example/singleton/IdGenerator1.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.ipipman.gof.example.singleton;
22

3-
// 饿汉式
3+
// 1.饿汉式
44
// 饿汉式的实现比较简单,在类加载的时候,instance 静态实例已经创建并初始化好了,所以 instance 实例是线程安全的;
55
// 不过,这样实现方式不支持延迟加载,初始化时可能会耗性能;
66

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.ipipman.gof.example.singleton;
2+
3+
// 2.懒汉试
4+
// 有饿汉式就有懒汉式;
5+
// 懒汉式对于饿汉式的优势在于它支持延迟加载,不影响初始化性能;
6+
// 不过懒汉试缺点也很明显,我们给 getInstance() 加了一个 synchronized 锁,导致这个方法并发度很低,性能非常差;
7+
8+
import java.util.concurrent.atomic.AtomicLong;
9+
10+
public class IdGenerator2 {
11+
12+
private AtomicLong id = new AtomicLong(0);
13+
private static IdGenerator2 instance;
14+
15+
private IdGenerator2() {
16+
17+
}
18+
19+
public static synchronized IdGenerator2 getInstance() {
20+
if (instance == null) {
21+
instance = new IdGenerator2();
22+
}
23+
return instance;
24+
}
25+
26+
public Long getId() {
27+
return id.incrementAndGet();
28+
}
29+
30+
// TODO Testing...
31+
public static void main(String[] args) {
32+
IdGenerator2 idGenerator2 = IdGenerator2.getInstance();
33+
System.out.println(idGenerator2.getId());
34+
}
35+
36+
}

0 commit comments

Comments
 (0)