Android图片管理工具 弹窗 保活 音乐播放器 自定义View 计步器 项目框架

android中单例模式的优缺点

2019-06-26  本文已影响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();

    }

}

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

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

上一篇 下一篇

猜你喜欢

热点阅读