android中单例模式的优缺点

作者: 天使飞吧 | 来源:发表于2019-06-26 18:14 被阅读0次

1.饿汉式

public class TestSingleton {  

    private TestSingleton() {}  

    private static final TestSingleton single = new TestSingleton ();  

    //静态工厂方法   

    public static TestSingleton getInstance() {  

        return single;  

    }  

资源效率不高,类加载过程慢

2.懒汉式

 public class TestSingleton {  

        private TestSingleton() {}  

        private static TestSingleton single=null;  

        public static synchronized TestSingleton getInstance() {  

         if (single == null) {    

             single = new TestSingleton();  

         }    

        return single;  

        }  

    } 

懒汉式在单个线程中没有问题,但多个线程同事访问的时候就可能同时创建多个实例

3、双重检查机制

public class SingleTon {

    private static volatile SingleTon instance;

    private SingleTon() {}

    public static SingleTon getInstance() {

        if (instance == null) {

            synchronized (SingleTon.class) {

                if (instance == null) {

                    instance = new SingleTon();

                }

            }

        }

        return instance;

    }

}

优点:资源利用率高,线程安全

缺点:第一次加载时反应稍慢,在高并发环境下有缺陷

4,静态内部类(是线程安全的,也是推荐使用的)

public class SingleTon {

    private SingleTon() {}

    public static SingleTon getInstance(){

      return SingletonHolder.instance;

    }

    private static class SingletonHolder{

        private static final SingleTon instance = new SingleTon();

    }

}

优点:线程安全,节约资源

缺点:第一次加载时反应稍慢

相关文章

  • JAVA基础之单例

    JAVA单例的几种形式以及其优缺点。 Android 中的单例模式 - 简书 单例的定义:Singleton模式的...

  • LayoutInflater源码分析

    在《(-)Android中的单例模式》分析中,我们分析了Android中单例模式的实现,且以LayoutInfla...

  • 单例模式

    1.属性值可修改的单例模式 2.属性值不可修改的单例模式 优缺点: 优点: 在单例模式中,活动的单例只有一个实例,...

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • android中单例模式的优缺点

    1.饿汉式 public class TestSingleton { private TestSingleto...

  • iOS开发-单例(粒)模式的介绍和实战使用

    今天给同学们讲解一下单例模式在iOS开发中的使用以及单例模式的相关优缺点,那么废话不多说,直接上代码~ 单例模式介...

  • 单例模式的常用实现方式

    单例模式属于最常用的设计模式,Java中有很多实现单例模式的方式,各有其优缺点 实现方式对比 单例实现方式线程安全...

  • Android 架构师之路5 设计模式之单例模式

    Android 架构师之路 目录 前言 Java中单例(Singleton)模式是一种广泛使用的设计模式。单例模式...

  • 简单聊聊单例模式

    单例模式应该是Android开发中常用的一种设计模式。不仅我们经常用到,Android源码中也经常可以看到单例模式...

  • 单例设计模式

    单例设计模式是用的最多的设计模式,也是最简单的一中设计模式。下面来介绍下几种实现单例的方式,以及分析下各自的优缺点...

网友评论

    本文标题:android中单例模式的优缺点

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