多种单例模式

Posted 这个冬天有点冷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多种单例模式相关的知识,希望对你有一定的参考价值。

//1 懒汉,线程不安全
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}

    public static Singleton getInstance(){
        if(instance == null ) {
            instance = new Singleton();
        }

        return instance;
    }   
}

//2 懒汉,线程安全
public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}

    public static synchronized Singleton getInstance(){
        if(instance == null ) {
            instance = new Singleton();
        }

        return instance;
    }
}

//3 饿汉
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){}

    public static Singleton getInstance(){      
        return instance;
    }
}

//4 静态内部类
public class Singleton {
    private static class SingletonHolder {
        public static Singleton instance = new Singleton();
    }
    private Singleton(){}

    public static Singleton getInstance(){      
        return Singleton.SingletonHolder.instance;
    }
}

//5 枚举
public class Singleton {

    private Singleton(){}

    public static Singleton getInstance(){      
        return Single.instance.getInstance();
    }

    private static enum Single {
        instance;

        private  Singleton single;
        //JVM会保证此方法绝对只调用一次
        private Single(){
            single = new Singleton();
        }

        public Singleton getInstance(){
            return single;
        }
    }
}

//6 双重校验锁
public class Singleton {

    private static volatile Singleton instance = null;
    private Singleton(){}


    private static Singleton getInstance() {
        if(instance == null) {
            synchronized (Singleton.class) {
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

以上是关于多种单例模式的主要内容,如果未能解决你的问题,请参考以下文章

单例模式的多种实现

单例模式的多种玩法

Java单例模式 多种实现方式

java学习-单例模式的多种实现方式

聊聊“单例模式”的多种实现方式。

多种单例模式