zoukankan      html  css  js  c++  java
  • 单例模式

    最近面试问别人单例模式,结果发现自己对单例模式也是一知半解  所以这边记录一下

        单例模式     简单来说的意思就是   我们使用的对象及实例化  都是同一对象

        引用另一个文章的代码http://www.importnew.com/18872.html

    饿汉模式

        

    public class Singleton {   
        private static Singleton = new Singleton();
        private Singleton() {}
        public static getSignleton(){
            return singleton;
        }
    }

    这种做法不的缺点是:我们第一次实例化该单例的时候   不管我们是否需要  他都会new  一个对象给我们

    加入延时加载 懒汉模式

      

    public class Singleton {
        private static Singleton singleton = null;
        private Singleton(){}
        public static Singleton getSingleton() {
            if(singleton == null) singleton = new Singleton();
            return singleton;
        }
    }

    但是这种方法  是线程不安全的的

    加锁

      

    public class Singleton {
        private static volatile Singleton singleton = null;
    
        private Singleton(){}
    
        public static Singleton getSingleton(){
            synchronized (Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
            return singleton;
        }    
    }

    这种做法的话 效率又太低    

    volatile    修饰符可以看这篇文章http://www.importnew.com/24082.html

    加入双重锁

      

    public class Singleton {
        private static volatile Singleton singleton = null;
    
        private Singleton(){}
    
        public static Singleton getSingleton(){
            if(singleton == null){
                synchronized (Singleton.class){
                    if(singleton == null){
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }    
    }

    内部静态类

      

    public class Singleton {
        private static class Holder {
            private static Singleton singleton = new Singleton();
        }
    
        private Singleton(){}
    
        public static Singleton getSingleton(){
            return Holder.singleton;
        }
    }

    枚举写法

    public enum Singleton {
        INSTANCE;
        private String name;
        public String getName(){
            return name;
        }
        public void setName(String name){
            this.name = name;
        }
    }
    
  • 相关阅读:
    音视频之PCM转WAV(八)
    音视频之播放YUV数据(十二)
    音视频之视频录制(十)
    报错error: missing D__STDC_CONSTANT_MACROS / #define __STDC_CONSTANT_MACROS
    Vue组件广告滚动
    配置Vue中@符,出现路径提示
    iOS WKWebView后台崩溃问题排查
    vue element 静态分页
    vue Vue __ob__: Observer 取值
    csdn 复制代码
  • 原文地址:https://www.cnblogs.com/liaohongbin/p/8807528.html
Copyright © 2011-2022 走看看