java常用的模式—单例模式
为了保证某些消耗资源的类在程序中的唯一性,减少不必要的开销,我们需要使用单例模式。介绍几种常用的单例模式及优缺点:
饿汉单例模式
class Singleton{
private Static Singleton instance = new Singleon();
private Singleon(){
}
public static Singleton getInstance(){
return instance;
}
}
但是以上懒汉式单例的实现没有考虑线程安全问题,它是线程不安全的,并发环境下很可能出现多个Singleton实例,要实现线程安全,有以下三种方式,都是对getInstance这个方法改造,保证了懒汉式单例的线程安全:
1、在getInstance方法上加同步
public static synchronized Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
2、双重检查锁定
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
在jdk 1.5之前这种形式并不能很好的保证单例运行,可能在进入同步块之后,在实例化一部分之后(没有完全实例化)的时候被其他线程占用,所以这种方式不推荐。
3、静态内部类
class Singleton{
private Singleon(){
}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder{
private static Singleon INSTANCE= new Singleon();
}
}
这种比上面1、2都好一些,既实现了线程安全,又避免了同步带来的性能影响。
懒汉单例模式
class Singleton{
private Static Singleton instance = null;
private Singleon(){
}
public static Singleton getInstance(){
if(instance == null)
instance = new Singleon();
return instance;
}
}
还有一些枚举单例、容器单例模式等等在此处不再详细说了,推荐使用静态内部类的方式。