再谈MVP模式优化问题

来源:互联网 发布:直接淘宝代购找衣服 编辑:程序博客网 时间:2024/06/03 22:08

  所谓模式,既前人经验,后人拾而己用。作为一名coder,掌握常用的设计模式,可以帮助快速解决问题,把更多的时间用在梳理业务逻辑上。空对象模式虽未列入23种常用设计模式,但是它在编程中却是不可或缺的。这里我只是做简单的介绍并给出一个实际的使用场景,如有不解请自行实践。
Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators.
大多数面向对象的语言,如java或C#,引用都有可能是空的。而这些引用需要进行检查,以确保在调用任何方法之前不为空,因为不能在空引用上调用。没有使用null来表示传递对象的不存在,而是使用实现了预期的接口的一个对象,但其方法主体是空的。

对外暴露的组件接口

public interface Component {    void operate();}

组件实现方式A

public class ComponentImplA implements Component {    @Override    public void operate() {        Log.d(ComponentImplA.class.getSimpleName(), "just do yourself");    }}

组件实现方式B

public class ComponentImplB implements Component {    @Override    public void operate() {        Log.d(ComponentImplA.class.getSimpleName(), "just do yourself");    }}

组件默认实现(空实现)

public class NullComponent implements Component {    @Override    public void operate() {        // NO-OP    }}

组件工厂,用于根据组件类型生成相对应的组件

public final class ComponentFactory {    public static Component createComponent(String componentType) {        if ("A".equals(componentType)) {            return new ComponentImplA();        } else if ("B".equals(componentType)) {            return new ComponentImplA();        } else {            return new NullComponent();        }    }}

我觉得只要有些许编程经验都能够理解这个模式,但是灵活运用确实另外一说了,以下是在android开发中的使用情景:

Presenter需要持有View的句柄(Activity或者Fragment),我们在Activity生命周期onDestroy()中需要通知Presenter对Activity的句柄进行释放,但是如果Presenter中如果存在某个子线程后台一直运行,待返回结果需要对View进行更新时就需要对是否继续持有View句柄进行判定,这个判定过程稍显臃肿,而此时我们可以采用NullObject模式,在detachView时动态生成一个空对象,我们调用该对象的操作都会是空实现。

public class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V> {    private V view;    @Override    public void attachView(V view) {        this.view = view;    }    @NonNull    public V getView() {        if (view == null) {            throw new NullPointerException("MvpView reference is null. Have you called attachView()?");        }        return view;    }    @Override    public void detachView(boolean retainInstance) {        if (view != null) {            Type[] types =                    ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();            Class<V> viewClass = (Class<V>) types[0];            view = NoOp.of(viewClass);        }    }}

写在最后的话,作为程序员的你我,不要浮躁,踏踏实实,一步一个脚印的学习,总会有质变的时候—–要相信总会守得云开见月明。

1 0