Head First 设计模式笔记:单例模式

时间:2023-03-08 21:49:29
单例模式
确保一个类只有一个实例,并提供一个全局访问点。

类图:

Singleton

static uniqueInstance

//其他属性...

static getInstance()

//其他方法...

使用单例模式得需要考虑到多线程环境下的问题,以下为几种解决方法:

1、同步getInstance()

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

同步一个方法可能造成程序执行效率下降100倍,所带来的性能问题要慎重考虑。

2、使用“急切”创建实例,即在静态初始化器里创建实例

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

3、使用“双重检查加锁”,在getInstance()中减少使用同步(该方法不适用于java1.4及之前的版本)

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;
}