抽mvp

作者: 君袅 | 来源:发表于2019-03-25 08:17 被阅读0次

    第一版:

    Activity

    public abstract class BaseActivity<P extends BasePresenter,V extends BaseMvpView> extends AppCompatActivity {
    
        protected P presenter;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(getLayoutId());
            ButterKnife.bind(this);
            presenter=initPresenter();
            if(presenter != null){
                presenter.attachView((V)this);
            }
            initView();
            initData();
            initListener();
    
        }
    
        protected void initListener() {
        }
    
        protected void initData() {
        }
    
        protected void initView() {
    
        }
        protected abstract P initPresenter();
    
        protected abstract int getLayoutId();
    }
    

    fragment

    public abstract class BaseFragment<P extends BasePresenter,V extends BaseMvpView> extends Fragment {
    
        protected P presenter;
        private Unbinder unbinder;
        private View view;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
            presenter=initPresenter();
            if(presenter != null){
                presenter.attachView((V)this);
            }
            if(view == null){
                view = inflater.inflate(getLayoutID(),null);
                unbinder = ButterKnife.bind(this, view);
                initView(view);
                initData();
            }else {
                unbinder = ButterKnife.bind(this, view);
            }
            return view;
        }
    
        protected void initData() {}
    
        protected void initView(View view) {}
    
        protected abstract P initPresenter();
    
        protected abstract int getLayoutID();
    
        @Override
        public void onDestroy() {
            super.onDestroy();
           unbinder.unbind();
           if(presenter !=null){
               presenter.onDestroy();
           }
    
        }
    }
    
    

    Model

    public abstract class BaseModel {
        protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
        public void onDestory() {
            //掐断所有的网络
            mCompositeDisposable.clear();
        }
    }
    

    View

    public interface BaseMvpView {
    }
    

    Presenter

    public abstract class BasePresenter<V extends BaseMvpView>{
        protected V view;
    
        public void attachView(V view){
            this.view=view;
        };
    
        public BasePresenter(){
            initModel();
        }
    
        protected abstract void initModel();
    
    
        protected ArrayList<BaseModel> mModels=new ArrayList<>();
    
        public void onDestroy() {
            view = null;
            if (mModels.size()>0){
                for (BaseModel model :mModels) {
                    model.onDestory();
                }
            }
        }
    
    }
    

    接口回调

    public interface SynTony<B> {
        /*
         *回调成功
         * */
        void RequestSucceed(B bean);
    
        /*
         * 回调失败
         * */
        void RequestFailed(String string);
    }
    

    第二版:

    image.png

    --------------------------------------抽取的base层--------------------

    1.Application07注册获取上下文

    public class Application07 extends Application {
    
        private static Application07 mApplication;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mApplication = this;
        }
    
        public static Application07 getApplication(){
            return mApplication != null ? mApplication : null;
        }
    
        public static Context getAppContext(){
            return mApplication.getApplicationContext();
        }
    }
    

    2.BaseActivity 继承AppCompatActivity:

    public class BaseActivity extends AppCompatActivity {
    
        private Application07 mApplication07;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mApplication07 = (Application07) getApplication();
            Log.e("我的类名是--------", "onCreate: " + this.getClass().getSimpleName());
        }
    
        public void showToast(String content) {
            Toast.makeText(getApplicationContext(), content, Toast.LENGTH_SHORT).show();
        }
    }
    

    3.BaseMvpActivity用来抽取V层基类

    public abstract class BaseMvpActivity<P extends BasePresenter,M> extends BaseActivity implements ICommonView {
    
        private Unbinder mBind;
        public P mPresenter;
        public M mModel;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(getLayoutID());
            mBind = ButterKnife.bind(this);
            mPresenter=getPresenter();
            mModel=getModel();
            mPresenter.attach(this,(ICommonModel)mModel);
            initView();
            initData();
        }
    
        public void initData() {}
    
        public void initView() {}
    
        protected abstract M getModel();
    
        protected abstract P getPresenter();
    
        protected abstract int getLayoutID();
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            mBind.unbind();
            mPresenter.detach();
        }
    
    }
    

    4.BasePresenter是P层的基类

    public class BasePresenter<M extends ICommonModel, V extends ICommonView> {
    
        private WeakReference<V> view;
        private WeakReference<M> model;
    
        public void attach(V view, M model) {
            this.view = new WeakReference<>(view);
            this.model = new WeakReference<>(model);
        }
    
        public void detach() {
            if (view != null) {
                view.clear();
                this.view = null;
            }
            if (model != null) {
                model.clear();
                this.model = null;
            }
        }
    
        public V getView() {
            return view != null ? view.get() : null;
        }
    
        public M getModel() {
            return model != null ? model.get() : null;
        }
    
    }
    

    5.M层的接口

    public interface ICommonModel<T> {
        void getData(ICommonView view,int whichApi,T... t);
    }
    

    6.P的接口

    public interface ICommonPresenter<T> {
        void getData(int whichApi,T... t);
    }
    

    7.V的接口

    public interface ICommonView<T> {
        void onError(Throwable e);
        void onResponse(int whichApi,T... t);
    }
    

    8.fragent的基层

    public abstract class BaseFragment<P extends BasePresenter,M > extends Fragment implements ICommonView{
    
        public P mPresenter;
        public M mModel;
        private Unbinder mBind;
        private View mView;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
            mPresenter=getPresenter();
            mModel = getModle();
            if(mPresenter!=null){
                mPresenter.attach(this, (ICommonModel) mModel);
            }
            if(mView == null){
                mView = inflater.inflate(getLayoutID(), null);
                mBind=ButterKnife.bind(this,mView);
                initView(mView);
                initData();
            }else {
                mBind=ButterKnife.bind(this,mView);
            }
            return mView;
        }
    
    
    
        public void initData() {}
        protected abstract void initView(View view);
        protected abstract int getLayoutID();
        protected abstract M getModle();
        protected abstract P getPresenter();
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            mBind.unbind();
            if(mPresenter!=null){
                mPresenter.dotach();
            }
        }
    }
    
    

    ----------------------------------------------------------##请求接口-----------------------------------------------------------
    1.项目中的时候会用不同的一套网络地址,方便更改

    public class NetConfig {
        public static String BASEURL;
        public static int type = 2;
    
        static {
            if (type == 1) {
                BASEURL = "www.baidu.com/";
            } else if (type == 2) {
                BASEURL = "http://gank.io/";
            } else {
                BASEURL = "";
            }
        }
    }
    

    2.请求接口

    public interface INetService {
    
        @GET("api/data/%E7%A6%8F%E5%88%A9/10/{pageNum}")
        @Headers("User-Agent:rxl")
        Observable<ImageInfo> getImage(@Path("pageNum") int page);
    }
    

    --------------------------------------------------------------使用mvp------------------------------------------------------------------------------

    1.P层

    public class CommonPresenter extends BasePresenter implements ICommonPresenter,ICommonView {
        @Override
        public void getData(int whichApi, Object... t) {
            if(getModel() != null){
                getModel().getData(this,whichApi,t);
            }else {
                Log.e("net error","found error when excute netWork to used getModel():, "+whichApi);
            }
        }
    
        @Override
        public void onError(Throwable e) {
            getView().onError(e);
        }
    
        @Override
        public void onResponse(int whichApi, Object[] o) {
             if(getView() != null){
                 getView().onResponse(whichApi,o);
             }else {
                 Log.e("onResponse error","getView() found error when onResponse  :"+whichApi);
             }
        }
    
    
    }
    

    2.M层(因为我们为了代码的简写所以一般一个模块用一个M层请求数据)

    public class TestModel implements ICommonModel {
        int page=1;
    
        @Override
        public void getData(ICommonView view, int whichApi, Object[] t) {
            switch (whichApi) {
                case ApiConfig.TESTAPI:
    
                   final int loadMode = (int)t[0];
                    NetManager.getNetManager().netMethod(NetManager.getNetManager().getNetService().getImage(loadMode
                            == LoadConfig.LOADMORE ? page++ : 1), view, whichApi, loadMode);
    
                    break;
                case ApiConfig.TESTAPI_2:
                    break;
            }
        }
    

    创建一个ApiConfig 用来标记加载的那个数据

    public class ApiConfig {
        public static final int TESTAPI = 0;
        public static final int TESTAPI_2 = 1;
    }
    

    用来LoadConfig用来标记请求状态

    public class LoadConfig {
        //正常请求
        public static final int NORMAL = 100;
        //刷新
        public static final int REFRESH = 101;
        //加载更多
        public static final int LOADMORE = 102;
    }
    

    3.V层的使用

    public class SplashActivity extends BaseMvpActivity<CommonPresenter,TestModel> implements ICommonView, XRecyclerView.LoadingListener {
    
        @BindView(R.id.recyclerView)
        XRecyclerView recyclerView;
        List<ImageInfo.ResultsBean> mBeanList = new ArrayList<>();
        private ImageAdapter mAdapter;
    
        @Override
        public int getLayoutId() {
            return R.layout.activity_splash;
        }
    
        @Override
        public void initData() {
            mPresenter.getData(ApiConfig.TESTAPI, LoadConfig.NORMAL);
            mPresenter.getData(ApiConfig.TESTAPI_2, LoadConfig.NORMAL);
        }
    
        @Override
        public CommonPresenter getPresenter() {
            return new CommonPresenter();
        }
    
        @Override
        public TestModel getModel() {
            return new TestModel();
        }
    
        @Override
        public void initView() {
            StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(manager);
            recyclerView.setLoadingListener(this);
            mAdapter = new ImageAdapter(mBeanList, this);
            recyclerView.setAdapter(mAdapter);
        }
    
        @Override
        public void onError(Throwable e) {
            showToast(e.getMessage());
        }
    
        @Override
        public void onResponse(int whichApi, Object[] t) {
            switch (whichApi) {
                case ApiConfig.TESTAPI:
                    ImageInfo info = (ImageInfo) t[0];
                    int loadType = (int) t[1];
                    if (loadType == LoadConfig.REFRESH) {
                        recyclerView.refreshComplete();
                        mBeanList.clear();
                    } else if (loadType == LoadConfig.NORMAL) recyclerView.loadMoreComplete();
                    mBeanList.addAll(info.getResults());
                    mAdapter.notifyDataSetChanged();
                    break;
                case ApiConfig.TESTAPI_2:
    
                    break;
            }
    
        }
    
        @Override
        public void onRefresh() {
            mPresenter.getData(ApiConfig.TESTAPI, LoadConfig.REFRESH);
        }
    
        @Override
        public void onLoadMore() {
            mPresenter.getData(ApiConfig.TESTAPI, LoadConfig.LOADMORE);
        }
    }
    

    ----------------------------------------M层中使用啦对retrofit的抽取--------------------------------------------------------------

    NetManager 抽取

    public class NetManager {
    
        private static volatile NetManager sNetManager;
    
        private NetManager() {
        }
    
        public static NetManager getNetManager() {
            if (sNetManager == null) {//考虑效率问题
                synchronized (NetManager.class) {
                    if (sNetManager == null) {//考虑多个线程问题
                        sNetManager = new NetManager();
                    }
                }
            }
            return sNetManager;
        }
    
        public INetService getNetService() {
            INetService service = new Retrofit.Builder()
                    .baseUrl(NetConfig.BASEURL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build().create(INetService.class);
            return service;
        }
    
        public <T> void netMethod(Observable<T> observable, final ICommonView view, final int whichApi, final int p) {
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver() {
                        @Override
                        public void onNetError(Throwable e) {
                            view.onError(e);
                        }
    
                        @Override
                        protected void onNetSuccess(Object value) {
                            view.onResponse(whichApi, value, p);
                        }
                    });
        }
    
    }
    

    订阅

    public abstract class BaseObserver implements Observer {
    
        private Disposable d;
    
        public abstract void onNetError(Throwable e);
    
        protected abstract void onNetSuccess(Object value);
    
        @Override
        public void onSubscribe(Disposable d) {
            this.d = d;
        }
    
        @Override
        public void onNext(Object value) {
            onNetSuccess(value);
            dispose();
        }
    
        @Override
        public void onError(Throwable e) {
            onNetError(e);
            dispose();
        }
    
        @Override
        public void onComplete() {
    
        }
    
        private void dispose() {
            if (d != null && !d.isDisposed()) {
                d.dispose();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:抽mvp

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