想必单例模式是最简单的 设计模式了防止对象重复创建消耗资源 比如创建网络请求的时候不必每次都去创建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();
}
}
网友评论