- 动机:对于系统来说,某些类只需要有一个实例或必需只能有一个实例(a.降低资源消耗;b.减少对象创建消耗的时间;c.减轻GC压力)
- 结构:
3.优缺点
-
- 优点:
- 提供了对惟一实例的受控访问。
- 节省系统资源
- 缺点:
- 由于单例模式中没有抽象层,因此单例类的扩展有很大的困难
- 单例类的职责过重
- 滥用单例将带来一些负面问题,如为了节省资源将数据库连接池对象设计为单例类,可能会导致共享连接池对象的程序过多而出现连接池溢出
- 优点:
4.用例:任务管理器、ID生成器、计时工具、Runtime
5.代码:
package
cn.com.tnjun.singlerow;
/**
* 饿汉单列模式(若单列创建比较慢会导致系统启动变慢)
*
@author
ilmlife(ilmlife @163.com)
*
<pre>
2013
-
12
-
15下午10:47:15
</pre>
*/
public
class
Singleton {
private
static
Singleton
singleton
=
new
Singleton();
private
Singleton(){
//same function as singlerow
}
public
static
Singleton getInstance(){
return
singleton
;
}
}
/**
* 懒汉单列模式(懒加载方式:在获取实例时,竞争越大,耗时越多。且只有第一次需要同步)
*
@author
ilmlife(ilmlife @163.com)
*
<pre>
2013
-
12
-
15下午10:47:15
</pre>
*/
public
class
Singlerow {
private
static
Singlerow
singlerow
;
private
Singlerow(){
//防止被直接new实例化
}
/**
* synchronized防止线程产生多个实例
*
@return
Singlerow
*/
public
static
synchronized
Singlerow getInstance(){
if
(
singlerow
==
null
){
singlerow
=
new
Singlerow();
}
return
singlerow
;
}
}
/**
* 双重检查锁(参见单例模式(双重检查锁之无序写入)
)
*
@author
ilmlife(ilmlife @163.com)
*
<pre>
2013
-
12
-
15下午10:47:15
</pre>
*/
public
class
Singlerow {
private
static
Singlerow
singlerow
;
private
Singlerow(){
//防止被直接new实例化
}
/**
* synchronized防止线程产生多个实例
*
@return
Singlerow
*/
public
static
Singlerow getInstance(){
if
(
singlerow
==
null
){
synchronized
(Singlerow.
class
) {
if
(
singlerow
==
null
){
singlerow
=
new
Singlerow();
}
}
}
return
singlerow
;
}
}
/**
* 内部类延迟加载机制(使用内部类避免使用同步关键字)
*
@author
tnjun(tnjun123456@163.com)
*
<pre>
2013
-
11
-
9
</pre>
*/
public
class
SingleInner {
private
SingleInner(){}
private
static
class
SingleHolder{
private
static
SingleInner
instance
=
new
SingleInner();
}
public
static
SingleInner getInstance(){
return
SingleHolder.
instance
;
}
}