设计模式之单例模式

1、饿汉式

1
2
3
4
5
6
7
8
9
10
11
public class HungerSingleObject {
private static HungerSingleObject instance = new HungerSingleObject();
private HungerSingleObject() {
}
public static HungerSingleObject getInstance() {
return instance;
}
public void showMessage() {
System.out.println("this is singleton pattern");
}
}

2、懒汉式 线程不安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LazySingleObject {
private static LazySingleObject instance;
private LazySingleObject() {

}
public static LazySingleObject getInstance() {
if(instance == null) {
instance = new LazySingleObject();
}
return instance;
}
public void showMessage() {
System.out.println("this is lazy single pattern");
}
}

3、懒汉式 线程安全 加同步锁

1
2
3
4
5
6
7
8
9
10
11
12
13
public class SyncLazySingleObject {
private static SyncLazySingleObject instance;
private SyncLazySingleObject() {}
public static synchronized SyncLazySingleObject getInstance() {
if(instance == null) {
instance = new SyncLazySingleObject();
}
return instance;
}
public void showMessage() {
System.out.println("this is synchronized lazy single pattern");
}
}