单例模式 | Eddie'Blog
单例模式

单例模式

eddie 491 2020-07-15

目录

扩展图

graph TD;   A[实现方式]-->B[懒汉式];   A-->C[饿鬼式];   A-->D[加类锁懒汉式];   A-->E[双重判断加锁懒汉式];

两种基础方式

懒汉式

/**
 * @author eddie.lee
 * @Package com.example.demo
 * @ClassName Singleton
 * @description 懒汉单例: 不是线程安全的
 * @date created in 2020-07-15 11:24
 * @modified by
 */
public class Singleton {

	private static Singleton singleton = null;

	private Singleton() {
	};

	public static Singleton getInstance() {
		if (null == singleton) {
			singleton = new Singleton();
			System.out.println(singleton);
		}
		return singleton;
	}
}

饿鬼式

/**
 * @author eddie.lee
 * @Package com.example.demo
 * @ClassName HungrySingleton
 * @description 饿鬼单例: 简单快捷
 * @date created in 2020-07-15 11:41
 * @modified by
 */
public class HungrySingleton {

    private static HungrySingleton hungrySingleton = null;

    public HungrySingleton() {
    }

    public static HungrySingleton getInstance() {
        hungrySingleton = new HungrySingleton();
        return hungrySingleton;
    }
}

加类锁懒汉式

/**
 * @author eddie.lee
 * @Package com.example.demo
 * @ClassName SingletonThree
 * @description 加锁的懒汉式
 * @date created in 2020-07-15 11:58
 * @modified by
 */
public class SingletonThree {

	private static SingletonThree singletonThree = null;

    public SingletonThree() {
    }

    public static SingletonThree getInstance() {
        synchronized (SingletonThree.class) {
            if (null == singletonThree) {
                singletonThree = new SingletonThree();
                System.out.println(singletonThree);
            }
        }
        return singletonThree;
    }
}

双重判断加锁的懒汉式

/**
 * @author eddie.lee
 * @ProjectName monitor_tuning
 * @Package com.example.demo
 * @ClassName DoubleCheckLockSingleton
 * @description 双重判断加锁的懒汉式
 * @date created in 2020-07-15 13:50
 * @modified by
 */
public class DoubleCheckLockSingleton {

	private static DoubleCheckLockSingleton doubleCheckLockSingleton = null;

	private DoubleCheckLockSingleton() {
	}

    /**
     * 1. 解决线程安全
     * 2. 判断单例对象已经不为空,就直接返回单例对象,就不需要判断线程同步锁的构造单例
     * 3. 双重校验锁,其实为了减少同步锁次数,提高效率
     */
	private static DoubleCheckLockSingleton getInstance() {
		if (null == doubleCheckLockSingleton) {
			synchronized (DoubleCheckLockSingleton.class) {
				if (null == doubleCheckLockSingleton) {
					doubleCheckLockSingleton = new DoubleCheckLockSingleton();
				}
			}
		}
		return doubleCheckLockSingleton;
	}
}


# Java