以前使用单例模式,总是使用传统的懒汉式,饿汉式两种,但是后来觉的这两种都存在一定的问题,后来又有了双重检测问题,但是今天发现猿友们这个更靠谱,通过金台内部类来写单例,觉的很不错,指的学习,
package test.dmdfchina.com.rxjavamvp;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by mkt on 2018/1/18.
*/
public class SingleInstance {
private static final String baseUrl="http://dmdf.com";
//将构造方法私有化
private SingleInstance(){}
/*通过内部类来初始化外部类的引用*/
private static class InnerClass{
private static final SingleInstance instance=new SingleInstance();
}
/*对外界提供的方法*/
public static SingleInstance getInstance(){
return InnerClass.instance;
}
private ApiService mApiService=null;
public ApiService getmApiService(){
if (mApiService==null){
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
mApiService=retrofit.create(ApiService.class);
return mApiService;
}
return mApiService;
}
}
其中ApiService.java,使用retrofit实现网络请求,
package test.dmdfchina.com.rxjavamvp;
import java.util.Observer;
import retrofit2.http.Field;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
/**
* Created by mkt on 2018/1/18.
*/
public interface ApiService {
/*post请求*/
@POST("/manager.php?m=Admin&c=OfflineLesson&a=getSchoolLesson")
Observer getData(@Field("id") String id, @Field("l_id") int l_id);
/*get请求*/
@GET("/manager.php?m=Admin&c=OfflineLesson&a=getSchoolLesson")
Observer getNetGet(@Query("id") String id, @Query("t_id") int t_id);
}
以后单例可以试着这种方式了,仅供自己使用!