1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
//饿汉式
public
class
EagerSingleton
{
//一上来就创建实例,所以叫饿汉
private
static
final
EagerSingleton m_instance =
new
EagerSingleton();
private
EagerSingleton() { }
public
static
EagerSingleton getInstance()
{
return
m_instance;
}
}
//懒汉式
public
class
LazySingleton
{
private
static
LazySingleton
m_instance =
null
;
private
LazySingleton() { }
synchronized
public
static
LazySingleton getInstance(){
//实例为空的时候才创建,否者直接拿来用,所以是懒汉
if
(m_instance ==
null
)
{
m_instance =
new
LazySingleton();
}
return
m_instance;
}
}
|
写一个Singleton
最新推荐文章于 2022-04-21 23:38:19 发布