File tree Expand file tree Collapse file tree 4 files changed +93
-0
lines changed
java-des/src/com/java/design/singleton Expand file tree Collapse file tree 4 files changed +93
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .java .design .singleton ;
2
+
3
+ /**
4
+ * 单例模式的实现:饿汉式,线程安全 但效率比较低
5
+ */
6
+ public class SingletonA {
7
+
8
+ private SingletonA () {
9
+ }
10
+
11
+ private static final SingletonA instance = new SingletonA ();
12
+
13
+ public static SingletonA getInstance () {
14
+
15
+ return instance ;
16
+ }
17
+
18
+ }
Original file line number Diff line number Diff line change
1
+ package com .java .design .singleton ;
2
+
3
+ /**
4
+ * 单例模式的实现:饱汉式,非线程安全
5
+ */
6
+ public class SingletonB {
7
+
8
+ // 防止实例化
9
+ private SingletonB () {
10
+
11
+ }
12
+
13
+ // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)
14
+ private static SingletonB instance ;
15
+
16
+ // 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题)
17
+ // 加上 synchronized 保证线程安全
18
+ public static synchronized SingletonB getInstance () {
19
+
20
+ if (instance == null ) {
21
+ instance = new SingletonB ();
22
+ }
23
+ return instance ;
24
+ }
25
+ }
Original file line number Diff line number Diff line change
1
+ package com .java .design .singleton ;
2
+
3
+ /**
4
+ * 单例模式最优方案 线程安全 并且效率高
5
+ */
6
+ public class SingletonC {
7
+
8
+ private SingletonC () {
9
+
10
+ }
11
+
12
+ // 定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
13
+ private static volatile SingletonC instance ;
14
+
15
+ public static SingletonC getInstance () {
16
+ if (instance == null ) {
17
+ // 同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
18
+ synchronized (SingletonC .class ) {
19
+ if (instance == null ) {
20
+ instance = new SingletonC ();
21
+ }
22
+ }
23
+ }
24
+ return instance ;
25
+ }
26
+ }
Original file line number Diff line number Diff line change
1
+ package com .java .design .singleton ;
2
+
3
+ /**
4
+ * 静态内部类
5
+ *
6
+ * @author Administrator
7
+ *
8
+ */
9
+ public class SingletonD {
10
+
11
+ private static class SingletonHolder {
12
+
13
+ private static final SingletonD INSTANCE = new SingletonD ();
14
+ }
15
+
16
+ private SingletonD () {
17
+
18
+ }
19
+
20
+ public static SingletonD getInstance () {
21
+
22
+ return SingletonHolder .INSTANCE ;
23
+ }
24
+ }
You can’t perform that action at this time.
0 commit comments