Java单例模式的实现

1、懒汉式,线程安全

public class Singleton {

	private static Singleton instance;
	public Singleton() {
		// TODO Auto-generated constructor stub
	}
	public static synchronized Singleton getInstance(){
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

2、饿汉式

public class Singleton {

	private static final Singleton instance = new Singleton();
	public Singleton() {
		// TODO Auto-generated constructor stub
	}
	public static Singleton getInstance(){
		return instance;
	}
}


3、双重检验锁

public class Singleton {

	private static volatile Singleton instance;//加上volatile取消jvm的重排序优化
	public Singleton() {
		// TODO Auto-generated constructor stub
	}
	public static Singleton getInstance(){
		if (instance == null) {                 //第一次检验
			synchronized (Singleton.class) {
				if (instance == null) {         //第二次检验
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}

4、内部静态类

public class Singleton {

	private static class SingletonHolder{
		private static final Singleton INSTANCE = new Singleton();
	}
	public Singleton() {
		// TODO Auto-generated constructor stub
	}
	public static Singleton getInstance(){
		return SingletonHolder.INSTANCE;
	}
}

5、枚举类

public enum Singleton {

	INSTANCE;
}


参考博客:

http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

http://javarevisited.blogspot.sg/2014/05/double-checked-locking-on-singleton-in-java.html

http://javarevisited.blogspot.sg/2012/07/why-enum-singleton-are-better-in-java.html

你可能感兴趣的:(单例模式)