单例模式

[TOC]

单例模式的写法

懒汉式

不加同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SingletonOne {
private static SingletonOne sInstance;
private SingletonOne() {
}
public static SingletonOne getInstance() {
if (sInstance == null) {
sInstance = new SingletonOne();
}
return sInstance;
}
}

同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SingletonTwo {
private static SingletonTwo sInstance;
private SingletonTwo() {
}
public synchronized static SingletonTwo getInstance() {
if (sInstance == null) {
sInstance = new SingletonTwo();
}
return sInstance;
}
}

双重检查锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class SingletonThree {
private static SingletonThree sInstance;
private SingletonThree() {
}
public static SingletonThree getInstance() {
if (sInstance == null) {
synchronized (SingletonThree.class) {
if (sInstance == null) {
sInstance = new SingletonThree();
}
}
}
return sInstance;
}
}

volatile(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class SingletonFour {
private static volatile SingletonFour sInstance;
private SingletonFour() {
}
public static SingletonFour getInstance() {
if (sInstance == null) {
synchronized (SingletonFour.class) {
if (sInstance == null) {
sInstance = new SingletonFour();
}
}
}
return sInstance;
}
}

饿汉式

1
2
3
4
5
6
7
8
9
10
11
public class SingletonFive {
private static SingletonFive sInstance = new SingletonFive();
private SingletonFive() {
}
public static SingletonFive getInstance() {
return sInstance;
}
}

静态内部类(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SingletonSix {
private SingletonSix() {
}
public static SingletonSix getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
public static final SingletonSix INSTANCE = new SingletonSix();
}
}

枚举

1
2
3
public enum SingletonSeven {
INSTANCE;
}

UniversalImageLoader分析

如果您觉得这篇文章不错,可以打赏支持下哦,谢谢