一、思路:
- 1.接口过多—通过把Presenter,Model,View抽取出抽象类BasePresenter,BaseModel,BaseView,并通过使用泛型
- 2.View的内存泄漏—通过使弱引用,在View销毁的时候,手动GC,让系统回收内存
二、核心代码实现
package com.example.basemvp.base;
import android.util.Log;
import java.lang.ref.WeakReference;
public abstract class BasePresenter<V extends BaseView, M extends BaseModel, C> {
private static final String TAG = "BasePresenter";
protected WeakReference<V> weakReference;
protected M model;
protected abstract M getModel();
protected abstract C getContract();
public BasePresenter() {
model = getModel();
}
protected V getView() {
if (weakReference != null) {
return weakReference.get();
}
return null;
}
public void bindView(V view) {
//使用弱应用
weakReference = new WeakReference<>(view);
Log.e(TAG, "bindView: " + weakReference);
}
//手动gc 让系统回收,以免内存泄漏
public void unBindView() {
Log.e(TAG, "unBindView: ");
if (weakReference != null) {
weakReference.clear();
weakReference = null;
}
System.gc();
}
}
package com.example.basemvp.base;
public abstract class BaseModel<P extends BasePresenter, C> {
protected abstract C getContract();
protected P presenter;
public BaseModel(P presenter) {
this.presenter = presenter;
}
}
package com.example.basemvp.base;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public abstract class BaseView<P extends BasePresenter, C> extends AppCompatActivity {
protected P presenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
presenter = getPresenter();
presenter.bindView(this);
}
protected abstract void init();
protected abstract C getContract();
protected abstract P getPresenter();
@Override
protected void onDestroy() {
super.onDestroy();
presenter.unBindView();
}
}
package com.example.basemvp.login.loginContract;
public interface LoginContract {
interface Model {
void execueLogin(String username, String pwd);
}
interface Presenter<T> {
void requestLogin(String username, String pwd);
void responesLogin(T data);
}
interface View<T> {
void handeLogin(T data);
}
}
三、代码传送门
https://gitee.com/daxiaa/MvpTest
网友评论