01-单列模式 [懒汉式 双重检查]

package com.design.patterns;

/**
 * 
 * @author Fighting
 * 懒汉式加载 线程安全 
 * 1.将类构造器私有化,防止new对象
 * 2.创建类变量
 * 3.提供公共获取对象的方法,实现双重检查
 */
public class DoubleCheckDemo {

	public static void main(String[] args) {
		System.out.println("双重检查");
		DoubleCheckSingleton lazyNotSafeSingleton = DoubleCheckSingleton.getInstance();
		DoubleCheckSingleton lazyNotSafeSingleton2 = DoubleCheckSingleton.getInstance();

		// 比较两个对象是否相等
		System.out.println(lazyNotSafeSingleton == lazyNotSafeSingleton2);

		// 查看两个对象的Hash值是否相同
		System.out.println(lazyNotSafeSingleton);
		System.out.println(lazyNotSafeSingleton2);
	}
}

class DoubleCheckSingleton{
	private DoubleCheckSingleton(){}
	
	//volatile保证变量可见性
	private static volatile DoubleCheckSingleton instance = null;
	private static Object object = new Object();
	
	public static DoubleCheckSingleton getInstance(){
		//一旦被初始化,后续的线程,则不会走进同步代码块
		if(instance == null){
			synchronized(object){
				if(instance == null){
					instance = new DoubleCheckSingleton();
				}
			}
		}
		
		return instance;
	}
}

[注:在此处volatile理解为可见性较好,至于其他理解可参考<<深入Java虚拟机>>]

你可能感兴趣的:(设计模式)