单例设计模式

1,单例设计模式
保证程序中只有一个实例。
1.1,饿汉(程序一运行,就开始初始化)

    public class Single {
        private static  Single mIntance = new Single();

        private Single(){

        }

        public static Single getIntance(){
            return mIntance;
        }
    }

1.2,懒汉

方案1:线程不安全

    public class Single {
        private static  Single mIntance ;

        private Single(){

        }

        public static Single getIntance(){
            if (mIntance==null){
                mIntance = new Single();
            }
            return mIntance;
        }
    }

方案2:线程安全,但是效率很低,每次getIntance 都需要经过同步锁的判断

    public class Single {
        private static  Single mIntance ;

        private Single(){

        }

        public static synchronized Single getIntance(){
            if (mIntance==null){
                mIntance = new Single();
            }
            return mIntance;
        }
    }

方案3:线程安全,效率也提高了,但是没有避免(1)执行顺序 (2)线程的不可见
可使用volatile 关键字 解决

    public class Single {
        //private static  Single mIntance ;
        private static volatile Single mIntance ;

        private Single(){

        }

        public static  Single getIntance(){
            if (mIntance==null){
                synchronized (Single.class){
                    if (mIntance==null){
                        mIntance=new Single();
                    }
                } 
            }
            return mIntance;
        }
    }

1.4 静态内部类实现单例

    public class Single {

        public static Single getIntance (){
            return SingleHolder.mIntance;
        }

        private static class SingleHolder{
            static final Single mIntance = new Single();
        }
    }

1.5 容器

    private static Map<String,Single> objMap = new HashMap<String,Single>();

    public static void registerService(String key, Single instance) {
        if (!objMap.containsKey(key) ) {
            objMap.put(key, instance) ;
        }
    }

    public static Single getService(String key) {
        return objMap.get(key) ;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、什么是单例模式 单例就是保证一个类仅有一个实例,并提供一个访问它的全局访问点。 二、单例的特点 1、单例只能...
    Ryan_Hoo阅读 205评论 0 0
  • 单例设计模式 单例设计模式介绍 单例设计模式的八种方法2.1 饿汉式(静态常量)2.1.1 实现步骤2.1.2 代...
    落在牛背上的鸟阅读 345评论 0 0
  • ###25.01_多线程(单例设计模式)(掌握) * 单例设计模式:保证类在内存中只有一个对象。 * 如何保证类在...
    SmileToLin阅读 189评论 0 0
  • 什么是设计模式? 是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。一些开发的套路,用于解决某一些特...
    Spring618阅读 672评论 0 0
  • 1.懒汉式 线程不安全,当有多个线程并行调用getInstance()的时候,就会创建多个实例。也就是说在多线程下...
    少一点阅读 171评论 0 0