再谈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); } }}
写在最后的话,作为程序员的你我,不要浮躁,踏踏实实,一步一个脚印的学习,总会有质变的时候—–要相信总会守得云开见月明。
- 再谈MVP模式优化问题
- MVP模式优化与进阶
- 浅谈Android中MVP模式用于实际项目中的问题与优化
- [android进阶篇]MVP模式优化,防止内存泄漏和空指针问题
- Android中的MVP模式及性能优化
- Android中的MVP模式及性能优化
- MVP设计模式的一次深入探索和优化
- android MVP模式简单实现并优化解绑
- MVP模式在Android实际项目中的应用和优化
- MVP模式
- MVP模式
- MVP模式
- MVP模式
- MVP模式
- MVP模式
- MVP模式
- mvp模式
- MVP模式
- 【函数】自定义函数统计字符个数
- Android源码 · IBinder
- 理解rostopic
- 搭建简易的c语言CGI和Apache服务器的开发环境
- jquery 操作 select
- 再谈MVP模式优化问题
- Java虚拟机类加载机制
- 【Unity&C#】委托学习经验 ------ 一种便利的委托泛型Action
- 关于Animation类中的方法setRepeatCount(int)方法使用
- 5-24 约分最简分式 (15分) c语言版
- 57.解决版本控制中 UserInterfaceState.xcuserstate 文件频繁变动
- android性能测试工具之dumpsys
- 1033. 旧键盘打字(20)
- javaScript"闭包" - (实例理解)