博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

六种单例模式

Posted on 2021-12-08 11:06  青柠时光  阅读(5)  评论(0)    收藏  举报

1.

/**
 * 1.饿汉式(静态常量)  (可用)
 * 类加载的时候就会实例化
 */
public class Singleton1 {

    private final static Singleton1 INSTANCE = new Singleton1();

    private Singleton1(){}

    public static Singleton1 getINSTANCE() {
        return INSTANCE;
    }
}

 

2.


/**
 * 2.饿汉式(静态代码块)  (可用)
 * 类加载的时候就会实例化
 */
public class Singleton2 {

    private final static Singleton2 INSTANCE;

    static {
        INSTANCE = new Singleton2();
    }

    private Singleton2(){}

    public static Singleton2 getINSTANCE() {
        return INSTANCE;
    }
}

 

3.


/**
 * 3.懒汉式(线程不安全)  (不可用)
 */
public class Singleton3 {

    private static Singleton3 INSTANCE;

    private Singleton3(){}

    public static Singleton3 getINSTANCE() {
        //如果两个线程同时进入,判断都为null,那么下面创建就会多次
        if (INSTANCE == null){
            INSTANCE = new Singleton3();
        }
        return INSTANCE;
    }
}

 

4.

/**
 * 4.懒汉式(线程安全)  (不推荐)
 */
public class Singleton4 {

    private static Singleton4 INSTANCE;

    private Singleton4(){}

    public synchronized static Singleton4 getINSTANCE() {
        //synchronized保护,那么两个线程无法同时进入,导致多次创建的问题。但是效率太低
        if (INSTANCE == null){
            INSTANCE = new Singleton4();
        }
        return INSTANCE;
    }
}

 

5.

 

/**
 * 5.懒汉式(线程不安全)  (不推荐)
 */
public class Singleton5 {

    private static Singleton5 INSTANCE;

    private Singleton5(){}

    public static Singleton5 getINSTANCE() {
        if (INSTANCE == null){
            //如果两个线程都到这里了,虽然创建上锁了,但是依旧会多次创建
            synchronized (Singleton5.class) {
                INSTANCE = new Singleton5();
            }
        }
        return INSTANCE;
    }
}

6.


/**
 * 6.懒汉式(线程安全)  (推荐)
 * 双重检查   推荐面试使用
 */
public class Singleton6 {

    /**
     * 1.创建一个空的对象
     * 2.调用对象的构造方法
     * 3.将实例赋值给引用
     * 如果CPU做了重排序,那么就会发生NPE
     */
    private volatile static Singleton6 INSTANCE;

    private Singleton6(){
    }

    public static Singleton6 getINSTANCE() {
        if (INSTANCE == null){
            synchronized (Singleton6.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton6();
                }
            }
        }
        return INSTANCE;
    }

}

 

 

 

7.

/**
 * 7.静态内部类  (可用)
 */
public class Singleton7 {


    public Integer a;

    private Singleton7(){
    }

    //内部类只有在
    private static class SingletonInstance{
        private static final Singleton7 INSTANCE = new Singleton7();
    }

    public static Singleton7 getINSTANCE() {
        return SingletonInstance.INSTANCE;
    }

}

8.

 


/**
 * 8.枚举单例  (可用)   防止反序列化
 * 这个类最简单
 */
public enum  Singleton8 {

    INSTANCE;

    private void whatever() {

    }

}