现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

HeadFirst 设计模式学习笔记5–单例模式

2012-07-19 07:54 工业·编程 ⁄ 共 1676字 ⁄ 字号 暂无评论

1.单例模式确保一个实例被创建,并且任意时刻都只有一个对象。它给了我们一个全局的访问点,又屏蔽了全局变量的缺点。可以被用来管理共享资源,比如数据库连接或线程池。特征是构造函数为私有,然后声明一个私有静态成员作为类对象,对外提供一个静态类方法创建该对象,在创建对象时会先判断是否已经创建,若是则直接返回已经创建的对象,若没有则创建新对象。

2.经典的单例模式如下:

public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}

这个是线程不安全的,因为在同一时刻可能两个线程都进入了getInstance中创建新的Singleton,导致唯一性不能保证。

3.多线程安全的单例模式如下:

public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}

使用一个synchronized 限定符对创建实例的方法进行同步,可以完成线程安全的需求,但是若已经创建后则同步这一动作是多余且降低效率的。若程序对这部分的效率不关注则使用该方法即可。

4.若总是使用该单例模式,则可以使用“急切”方式进行单例模式调用,利用了JVM加载类时会马上创建该实例的特性,这保证了线程安全,但是这又有和全局变量一样的问题——若这个对象耗资源很大,而程序在执行中又一直没有使用它,那么就造成了资源浪费:

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

5.一个比较周全的方式是用“双重检查加锁”的方式减少同步次数的同时又线程安全。注意JAVA5前不支持volatile关键字。

public class Singleton {
private volatile static Singleton uniqueInstance;//volatile 确保当uniqueInstance初始化为Singleton的实例时,多个线程可以正确的处理uniqueInstance变量。
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {//只有第一次才会执行这里面的代码。也就是说第一次为同步,后来就是不作为了——这就是我们要的效果。
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}

6.注意事项:

1)单例类不能被继承,因为Java中私有构造方法的无法扩展类。

2)和全局变量相比的优缺点,请参照“急切”和“延迟”两种单件模式实现的方式进行类比分析。

3)若使用多个类加载器,则可能导致单例失效。

给我留言

留言无头像?