package cn.datax.learning.design.patterns.creational.singleton;

public class SingleObject {

    private SingleObject() {}

    /**
     * 懒汉式加载
     */
    private static SingleObject instance;

    //线程不安全，不用于多线程使用（不推荐）
    public static SingleObject getInstance1() {
        if(instance == null) {
            instance = new SingleObject();
        }
        return instance;
    }

    //线程安全，同步方法（不推荐使用）
    public static synchronized SingleObject getInstance2() {
        if(instance == null) {
            instance = new SingleObject();
        }
        return instance;
    }

    //线程安全，同步代码块（不可用）
    public static SingleObject getInstance3() {
        if(instance == null) {
            synchronized(SingleObject.class) {
                instance = new SingleObject();
            }
        }
        return instance;
    }

    //线程安全，同步代码块，双重检查（推荐使用）
    private static volatile SingleObject instance2;
    public static SingleObject getInstance4() {
        if(instance2 == null) {
            synchronized(SingleObject.class) {
                if(instance2 == null) {
                    instance2 = new SingleObject();
                }
            }
        }
        return instance2;
    }

    /**
     * 饿汉式加载
     */
    private static SingleObject instance3 = new SingleObject();

    //静态常量（可用）
    public static SingleObject getInstance5(){
        return instance3;
    }

    //静态代码块（可用）
    private static SingleObject instance4;
    static{
        instance4 = new SingleObject();
    }
    public static SingleObject getInstance6(){
        return instance4;
    }

    //静态内部类（推荐用）
    private static class SingleObjectHolder {
        private static final SingleObject INTANCE = new SingleObject();
    }
    public static SingleObject getInstance7(){
        return SingleObject.SingleObjectHolder.INTANCE;
    }
}
