1、单例模式使用的场景:
确认一个类只能有一个对象的场景,避免消耗过多资源
比如:管理全局的网络请求。图片加载等等。
2、简单的单例模式示例:
public class Person{
private static Person mPerson;
//私有的构造方法,其他类不能创建这个类
private Person{
}
// 提供一个借口,其他类通过这个接口使用对象
public static Person getInstance(){
if(mPerson==null){
mPerson = new Person();
}
return mPerson;
}
//.....其他方法
public xx getxx(){}
}
//使用方法
xx xx = Person.getInstance().getxx();
``
//rxjava、Retrofit2 网络管理
//管理公共的api —– 单例模式
public class HttpManager {
private static HttpManager mHttpManager;
private HttpManager() {
}
public static HttpManager getInstance() {
if (null == mHttpManager) { //防止多个对象
mHttpManager = new HttpManager();
}
return mHttpManager;
}
public Api getApiService() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //返回Observable对象
.baseUrl(Constant.BASE_URL)
.build();
Api api = retrofit.create(Api.class);
return api;
}
}
“`
//同理,管理其他同一类,也可以这样。。方便管理,扩展