`
hzy3774
  • 浏览: 984945 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

Java中单例模式的几种常用方法

阅读更多

饿汉模式,易于理解,类被加载时就要初始化:

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

 简单懒汉模式,运行时加载,控制线程同步,但同步造成阻塞:

 

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

 双重检查可以避免过多阻塞:

 

public class Singleton {
    private static Singleton mInstance;

    private Singleton() {
    }

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

 通过内部静态类Holder来维护单例:

 

public class Singleton {
    private Singleton() {
    }

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

 使用枚举实现单例:

public enum Singleton {

    INSTANCE;

    private Singleton() {
    }

}

 好简单有木有。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics