单例模式-摘自《漫谈设计模式》

如果要保证系统里一个类最多只能存一个实例时,就需要单例模式
1)最简单的单例
[img]http://dl.iteye.com/upload/attachment/486570/1ebae9e0-634a-3230-8c85-ceed3ac9ba16.jpg[/img]
[img]http://dl.iteye.com/upload/attachment/486575/6303bf8e-2c27-37e6-a743-d1c416950aab.jpg[/img]

2)延迟创建
延迟实例化单例对象(static属性在加载类时就会被初始化),即在第一次使用该类的实例时才实例化
public class UnThreadSafeSingleton{
private static UnThreadSafeSingleton = null;
public static UnThreadSaceSingleton getInstance(){
if(instance==null){
instance = new UnThreadSafeSingleton();
}
return instance;
}

}
此方法不是线程安全的
[img]http://dl.iteye.com/upload/attachment/486584/6cce968c-1264-3579-b1ec-e31dda01c2ce.jpg[/img]

为了解决这个问题,在此方法上加synchronized关键字,即
public static [color=darkred]synchronized [/color]ThreadSafeSingleton getInstance(){....}

上述实现有performance问题,采用下面方法
3)Double-Check Locking


[img]http://dl.iteye.com/upload/attachment/486588/bbf4c584-144f-389c-83c9-6bf22970b095.jpg[/img]
[img]http://dl.iteye.com/upload/attachment/486592/4283e6ea-de57-3fdd-8e3d-4db17453ee45.jpg[/img]

4)Initialization on demand holder
这个也是线程安全的延迟的单例初始化方式
public class lazyLoadedSingleton{
private LazyLoadedSingleton(){}

[color=darkred] private static class LazyHolder{ //holds the singleton class
private static final LazyLoadedSingleton singletonInstance = new LazyLoadedSIngleton();
}[/color]

public static LazyLoadedSingleton getInstance(){
return LazyHolder.singletonInstance;
}
}

[img]http://dl.iteye.com/upload/attachment/486596/8ff3f928-e510-3451-8c71-56b9e0d4050c.jpg[/img]

5)Singleton的序列化

[img]http://dl.iteye.com/upload/attachment/486598/631a795b-6266-38e7-84ec-a0843393e78b.jpg[/img]
[img]http://dl.iteye.com/upload/attachment/486600/7b505618-6d89-318e-92bf-8679301c072d.jpg[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值