一般单例模式,没有考虑到同步问题:
1 package com.machinemind;
2
3 public class Singleton {
4 private static Singleton uniqueInstance = null;
5
6 private Singleton() {
7 }
8
9 public static Singleton getInstance() {
10 if (uniqueInstance == null) {
11 uniqueInstance = new Singleton();
12 }
13
14 return uniqueInstance;
15 }
16 }
17
加入同步锁,消耗资源多
1 package com.machinemind;
2
3 public class Singleton {
4 private static volatile Singleton uniqueInstance = null;
5
6 private Singleton() {
7 }
8
9 public static synchronized Singleton getInstance() {
10 if (uniqueInstance == null) {
11 uniqueInstance = new Singleton();
12 }
13
14 return uniqueInstance;
15 }
16 }
急切创建实例,如果没有用到对象,则浪费了资源
1 package com.machinemind;
2
3 public class Singleton {
4 private static Singleton uniqueInstance = new Singleton();
5
6 private Singleton() {
7 }
8
9 public static Singleton getInstance() {
10 if (uniqueInstance == null) {
11 uniqueInstance = new Singleton();
12 }
13
14 return uniqueInstance;
15 }
16 }
双重检查加锁法,优化了
1 package com.machinemind;
2
3 public class Singleton {
4 private static Singleton uniqueInstance = new Singleton();
5
6 private Singleton() {
7 }
8
9 public static Singleton getInstance() {
10 if (uniqueInstance == null) {
11 synchronized(Singleton.class) {
12 if (uniqueInstance == null) {
13 uniqueInstance = new Singleton();
14 }
15 }
16 }
17
18 return uniqueInstance;
19 }
20 }
按需创建
优点:私有的内部静态类
1 package com.machinemind;
2
3 public class Singleton
4 {
5 private Singleton() {
6 }
7
8 private static class Inner
9 {
10 static Singleton uniqueInstance = new Singleton();
11 }
12
13 public static Singleton getInstance()
14 {
15 return Inner.uniqueInstance;
16 }
17 }
posted on 2015-08-24 01:13
machinemind 阅读(55)
评论(0) 编辑 收藏 引用