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() {
    }

}

 好简单有木有。

猜你喜欢

转载自hzy3774.iteye.com/blog/2256020