Java单例模式几种实现方式

单例模式在很多种语言中都有用到并且有自己的实现方式.

这里列举几种Java的单例模式实现方法:

1. 枚举类型

2. 懒汉模式-内部类实现

3. 懒汉模式-双重检查


// 1: 枚举类型
public enum SingletonEnum {
	INSTANCE;
}

// 2: 勤快的汉子---你威武雄壮! 在加载类时就实例化对象, 利用Java的类加载的同步机制, 解决同步问题
class SingletonInLoad {
	private static SingletonInLoad instance;
	
	private SingletonInLoad() {};
	
	public static SingletonInLoad getInstance() {
		return instance;
	}
}

// 3: 懒汉模式-内部类实现
class SingletonInner {
	private SingletonInner() {}
	
	private static class SingletonInnerHolder {
		static final SingletonInner Instance = new SingletonInner();
	}
	
	public SingletonInner getInstance() {
		return SingletonInner.SingletonInnerHolder.Instance;
	}
}

// 4: 懒汉模式-双重检查
class SingletonDoubleCheck {
	private static volatile SingletonDoubleCheck instance;
	
	private SingletonDoubleCheck() {}
	
	public SingletonDoubleCheck getInstance() {
		if (instance == null) {
			synchronized (SingletonDoubleCheck.class) {
				if (instance == null) {
					instance = new SingletonDoubleCheck();
				}
			}
		}
		return instance;
	}
}




你可能感兴趣的:(Java)