Android MVP极限封装(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z2464342708m/article/details/79375346

上一篇博客Android MVP极限封装(一)简单介绍了MVP架构的封装过程,但是,这个封装并不完美,还存在着弊端,这篇博客怀着解决上一篇伴随而来的缺陷而写。
在Presenter模块里面,每次接口回调都要判断接口是否为空。如果是在项目中存在大量的Presenter,那么需要重复写N个判断去检测接口是否为空,按照Android开发的思想,这样的行为是不可取,那么,该如何改善呢?
想法很简单,那就是通过动态代理去维护回调接口:

/**
 * 抽象类 统一管理View层绑定和解除绑定
 *
 * @param <V>
 */
public class BasePresenter<V extends IView> implements IPresenter<V> {

    private WeakReference<V> weakView;
    protected V proxyView;

    public V getView() {
        return proxyView;
    }

    /**
     * 用于检查View是否为空对象
     *
     * @return
     */
    public boolean isAttachView() {
        return this.weakView != null && this.weakView.get() != null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void attachView(V view) {
        this.weakView = new WeakReference<V>(view);
        MvpViewInvocationHandler invocationHandler = new MvpViewInvocationHandler(this.weakView.get());
        // 在这里采用动态代理
        proxyView = (V) Proxy.newProxyInstance(
                view.getClass().getClassLoader(), view.getClass()
                        .getInterfaces(), invocationHandler);
        Proxy.getProxyClass(view.getClass().getClassLoader(),view.getClass().getInterfaces());
    }

    @Override
    public void dettachView() {
        if (this.weakView != null) {
            this.weakView.clear();
            this.weakView = null;
        }
    }

    private class MvpViewInvocationHandler implements InvocationHandler {

        private IView mvpView;

        public MvpViewInvocationHandler(IView mvpView) {
            this.mvpView = mvpView;
        }

        @Override
        public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
            if (isAttachView()) {
                return method.invoke(mvpView, arg2);
            }
            return null;
        }

    }

}

猜你喜欢

转载自blog.csdn.net/z2464342708m/article/details/79375346