Head First设计模式五-----单例模式(Singleton Pattern)

单例模式就是保证一个类只能创建一个实例,并提供一个可以访问它的全局入口给外界访问
但是使用全局变量虽然也能给外界提供全局访问,但是它无法保证只有一个实例

经典的单例模式:
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,此时才根据实例是否已存在而创建然后返回,但是它存在着线程安全的隐患,如果两个线程几乎同时访问getInstance方法,而之前没有其它线程访问过,那么此时两个线程都可能判断uniqueInstance = null,然后各自创建一个实例返回,这样就违返了单例模式的初衷和设想

最简单的解决方案:
直接将getInstance方法变为线程安全的,在前面加synchronized标识
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
}


[color=red]改进的解决方案:[/color]
1、如果性能不是主要考虑因素,那么就加synchronized标识
2、用提前加载代替延迟加载,直接给实例变量new一个实例,这样当单例类被JVM加载时自动创建这个实例,并且以后只返回它的引用,如下:
public class Singleton {
private static Singleton uniqueInstance = new Singleton();

private Singleton() {}

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

3、利用“双检测锁”降低同步的使用,提供性能(此解决方案只在JAVA5之后有效)
public class Singleton {
private volatile static Singleton uniqueInstance;
//volatile关键字保证当创建类实例时,多线程可以正确地处理该实例变量


private Singleton() {}

public static Singleton getInstance() {
if (uniqueInstance == null) {//检测是否已创建实例,如果没有则进入创建实例的同步锁
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值