Oct 08, 2023
浅谈单例
写在前头:希望你了解到的不仅是模式,而学会用OOP的眼光分析问题,解决问题。
静态单例
1
2
3
4
5
6
7
8
9
10
11
12//最简单的单例,静态单例,在第一次调用get_instance时对象已经创建
public class Singleton {
//kc:创建静态对象
private static Singleton instance = new Singleton();
//kc:构造函数私有
private Singleton() {}
public static Singleton getInstance() {
System.out.println("this is a call without create!");
return instance;
}
}延时加载单例(线程不安全)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17//延迟创建对象,第一次调用get_instance时才创建对象,线程不安全
public class delay_single {
public static delay_single instance;
private delay_single() {}
public static delay_single getInstance() {
//此处线程不安全
if(instance==null) {
instance= new delay_single();
System.out.println("this is a create call!");
}
System.out.println("this is a call");
return instance;
}
}延时加载单例(线程安全)
1
2
3
4
5
6
7
8
9
10
11
12
13
14//延迟创建,与delay_single的差别在于,引入了synchronized,线程安全
public class delay_singleton2 {
public static delay_singleton2 instance;
private delay_singleton2() {}
//synchronized关键字,保证线程安全
public static synchronized delay_singleton2 getInstance() {
if(instance==null) {
instance= new delay_singleton2();
}
return instance;
}
}