美文网首页
设计模式-单例模式

设计模式-单例模式

作者: 7ee4c95bcc68 | 来源:发表于2020-09-14 10:11 被阅读0次

    想必单例模式是最简单的 设计模式了防止对象重复创建消耗资源 比如创建网络请求的时候不必每次都去创建OkHttpClient 这个类我们就可以写一个单例

    1,饿汉式

    package com.wangtk.security.singletion;
    
    
    import okhttp3.OkHttpClient;
    
    public class OkHttpClientSingleton {
    
        private volatile static OkHttpClient singleton = new OkHttpClient();
    
    
        private OkHttpClientSingleton() {
        }
    
        public static OkHttpClient getSingleton() {
            return singleton;
        }
    
    }
    

    2,懒汉式

    package com.wangtk.security.singletion;
    
    import okhttp3.OkHttpClient;
    
    public class OkHttpClientSingleton {
    
        //注意 这个类变量一定要使用 volatile 关键字 可参考 The "Double-Checked Locking is Broken" Declaration
    
        private volatile static OkHttpClient singleton;
    
    
        private OkHttpClientSingleton() {
        }
    
        public static OkHttpClient getSingleton() {
            if (singleton == null) {
                synchronized (OkHttpClientSingleton.class) {
                    if (singleton == null) {
                        singleton = new OkHttpClient();
                    }
                }
            }
            return singleton;
        }
    }
    

    3、登记式/静态内部类

    package com.wangtk.security.singletion;
    
    
    import okhttp3.OkHttpClient;
    
    public class OkHttpClientSingleton {
    
    
        private OkHttpClientSingleton() {
        }
        
        public static final OkHttpClient getInstance() {
            return SingletonHolder.INSTANCE;
        }
    
        private static class SingletonHolder {
            private static final OkHttpClient INSTANCE = new OkHttpClient();
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式-单例模式

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