单件模式(Singleton Pattern)

--[i]Head First Design Pattern[/i]
定义:
单件模式确保一个类只有一个实例,并提供一个全局访问点。

适用地方:
eg:线程池(threadpool)、缓存(cache)、对话框、处理偏好设置和注册表(registry)的对象、日志对象、充当打印机、显卡等设备的驱动程序的对象。

三要素:对自身的引用,私有构造器,static getInstance()方法

关键字:
①延迟实例化②同步问题③double-check locking④类加载器


1、

public class Singleton{
private static Singleton uniqueInstance;

//other field

private Singleton(){} //私有构造器

public static Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}

//other useful methods
}


2、多线程情况下:
把getInstance()变成同步(synchronized)方法:

public class Singleton{
private static Singleton uniqueInstance;

//other field

private Singleton(){} //私有构造器

public static synchronized Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}

//other useful method
}

性能问题:同步一个方法可能使性能下降100倍

方案:
(1)“急切”创建实例,不使用延迟实例化
适用:应用程序总是创建并使用单件实例,或在创建和运行方面负担不太繁重

public class Singleton{
private static Singleton uniqueInstance = new Singleton();

private Singleton(){} //私有构造器

public static Singleton getInstance(){
return uniqueInstance;
}
}


(2)“双重检查加锁(double-checked locking)”,在getInstance()中减少使用同步

public class Singleton{
private volatile static Singleton uniqueInstance;

private Singleton(){} //私有构造器

public static Singleton getInstance(){
if(uniqueInstance == null){
synchronized (Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}

注:
1、volatile关键字:确保当uniqueInstance变量被初始化成Singleton实例时,多 个线程正确的处理uniqueInstance变量。
2、在1.4及更早版本的Java中,许多JVM对volatile关键字的实现会导致双重加锁失败的失效。


类加载器问题:
每个类加载器定义了一个命名空间,如果有两个以上的类加载器,不同的类加载器可能会加载同一个类,就可能会产生多个单件并存的现象。
若程序有多个类加载器又使用了单件模式:自行指定类加载器,并指定同一个类加载器。


序列化问题:
[i]study[/i]ing..
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值