Luckylau's Blog

设计模式之单例模式

单例模式是一个创建型的模式;

懒汉式(支持多线程)

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

饿汉式(支持多线程)

1
2
3
4
5
6
7
8
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
1
2
3
4
5
6
7
8
9
10
11
public class Singleton {
private static class SingletonHolder{
private static Singleton instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Luckylau wechat
如果对您有价值,看官可以打赏的!