美文网首页
Singleton - 单例模式

Singleton - 单例模式

作者: GeekAmI | 来源:发表于2018-07-13 16:09 被阅读30次

    1. show you the code:

    public class Singleton01 {
        private static Singleton01 instance;
        private Singleton01() {
        }
        // 线程不安全的单例实现
        public static Singleton01 getInstance(){
            if(instance == null)
                instance = new Singleton01();
            return instance;
        }
    }
    
    public class Singleton02 {
        private static Singleton02 instance;
        private Singleton02() {
        }
        //线程安全,但效率低
        public static synchronized Singleton02 getInstance(){
            if(instance == null)
                instance = new Singleton02();
            return instance;
        }
    }
    
    public class Singleton03 {
        private static Singleton03 instance = new Singleton03();
        private Singleton03() {
        }
        //线程安全,饿汉模式
        public static Singleton03 getInstance(){
            return instance;
        }
    }
    
    public class Singleton04 {
        private volatile static Singleton04 instance;//volatile 防止指令重排
        private Singleton04() {
        }
        //线程安全,双重检索模式
        public static Singleton04 getInstance() {
            if (instance == null) {
                synchronized (Singleton04.class) {
                    if (instance == null) {
                        instance = new Singleton04();
                    }
                }
            }
            return instance;
        }
    }
    
    // 内部静态类方式,线程安全
    public class Singleton05 {
        private Singleton05() {
        }
        private static class SingletonHolder{
            private static final Singleton05 INSTANCE = new Singleton05();
        } 
        public static Singleton05 getInstance(){
            return SingletonHolder.INSTANCE;
        }
    }
    
    //枚举模式
    public enum  SingletonEnum {
        INSTANCE;
    }
    
    1. 举例子
    饿汉模式 懒汉模式
    1. 左耳朵耗子的实现:https://coolshell.cn/articles/265.html
    2. http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

    相关文章

      网友评论

          本文标题:Singleton - 单例模式

          本文链接:https://www.haomeiwen.com/subject/yatdpftx.html