想必單例模式是最簡(jiǎn)單的 設(shè)計(jì)模式了防止對(duì)象重復(fù)創(chuàng)建消耗資源 比如創(chuàng)建網(wǎng)絡(luò)請(qǐng)求的時(shí)候不必每次都去創(chuàng)建OkHttpClient 這個(gè)類我們就可以寫一個(gè)單例
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 {
//注意 這個(gè)類變量一定要使用 volatile 關(guān)鍵字 可參考 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第股、登記式/靜態(tài)內(nèi)部類
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();
}
}