爱生活爱睡觉爱大笑
BlogJava
::
首页
::
新随笔
::
联系
::
聚合
::
管理
::
0 随笔 :: 2 文章 :: 0 评论 :: 0 Trackbacks
<
2025年7月
>
日
一
二
三
四
五
六
29
30
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
1
2
3
4
5
6
7
8
9
留言簿
给我留言
查看公开留言
查看私人留言
文章分类
(2)
AD(1)
(rss)
Pattern(1)
(rss)
文章档案
(2)
2008年10月 (2)
收藏夹
(3)
AD(2)
(rss)
Servlet(1)
(rss)
Spring
Struts2
搜索
最新评论
几种Singleton模式的java实现
Initialization on demand holder idiom
public
class
Singleton
{
//
Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected
Singleton()
{}
/** */
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE , not before.
*/
private
static
class
SingletonHolder
{
private
final
static
Singleton INSTANCE
=
new
Singleton();
}
public
static
Singleton getInstance()
{
return
SingletonHolder.INSTANCE;
}
}
Traditional simple way
public
class
Singleton
{
public
final
static
Singleton INSTANCE
=
new
Singleton();
//
Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected
Singleton()
{}
}
Java 5 solution
public
class
Singleton
{
private
static
volatile
Singleton INSTANCE;
//
Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected
Singleton()
{}
public
static
Singleton getInstance()
{
if
(INSTANCE
==
null
)
{
synchronized
(Singleton.
class
)
{
if
(INSTANCE
==
null
)
INSTANCE
=
new
Singleton();
}
}
return
INSTANCE;
}
}
The "Double-Checked Locking is Broken" Declaration.
The Enum-way
public
enum
Singleton
{
INSTANCE;
}
posted on 2008-10-30 14:16
重回疯人院
阅读(157)
评论(0)
编辑
收藏
所属分类:
Pattern
新用户注册
刷新评论列表
只有注册用户
登录
后才能发表评论。
网站导航:
博客园
IT新闻
Chat2DB
C++博客
博问
管理
Powered by:
BlogJava
Copyright © 重回疯人院