zoukankan      html  css  js  c++  java
  • Android MVP + 泛型,实现了友好VP交互及Activity潜在的内存泄露的优化

      Android MVP粗来已经有段时间了,在项目中我也多多少少用了一些,不得不说代码使用这种模式后,条例确实清晰了好多,整个流程看起来有点各司其职的感觉(另一种的java面向对象的方式)。

      不过这里是我在使用过程中遇到的一点小优化,直接进入代码来说吧!!!

     1 import java.lang.ref.Reference;
     2 import java.lang.ref.WeakReference;
     3 
     4 public class Presenter <T>{
     5 
     6     private Reference<T> mReference = null;
     7     
     8     public void onAttach(T view){
     9         mReference = new WeakReference<T>(view);
    10     };
    11     
    12     public boolean isAttach(){
    13         return null != mReference && null != mReference.get();
    14     }
    15     
    16     public void onDettach(){
    17         if(null != mReference){
    18             mReference.clear();
    19             mReference = null;
    20         }
    21     };
    22 }

      上述代码我这里简单说下,泛型的定义是为了给Activity及其子类声明使用(为啥这么说,因为presenter是专门针对View工作的,他的定义必须依赖于View的功能来完成.),这里可以看到我简单是采用了弱引用的方式去参数这个View的对对象引用,这里我主要考虑到万一Activity不走onDestroy方法,但是程序却退出了,现实中这种可能性很小,不过确实是存在的,弱引用主要就是为了这个目的而加的。

      紧接着一起来看BaseActivity

     1 public abstract class BaseActivity<V, T extends Presenter<V>> extends Activity{
     2 
     3     protected T mPresenter;
     4     
     5     @Override
     6     protected void onCreate(Bundle savedInstanceState) {
     7         super.onCreate(savedInstanceState);
     8         mPresenter = createPresener();
     9         mPresenter.onAttach((V) this);
    10     }
    11 
    12     
    13     @Override
    14     protected void onDestroy() {
    15         // TODO Auto-generated method stub
    16         super.onDestroy();
    17         mPresenter.onDettach();
    18     }
    19     
    20     protected abstract T createPresener();
    21 }

      这里可看到,这里由于是BaseActivity,我希望他去做的工作就是在Activty创建的时候先创建Presenter对象,并告知Presenter自己已经被创建,同时将自身注入给Presenter,以便于完成P到V的回调工作. T extent Presenter是为了保证createPrenter返回的事Presenter 的子类对象. 8行没有判空直接使用的目的是为了更好的使用MVP的思想,所以这里的抽象方法是不允许返回null的,这是我的个人设计,不过大家要是希望返回null,可以自己在进一步的坐下处理.

       之上的简单的VP交互,我是根据个人需求做的定义(Attach, Dettach, isAttach).

       

  • 相关阅读:
    Kubernetes
    桥接模式
    原型模式
    工厂模式
    生成器模式
    Java-Sentinel限流中间件
    python模拟发送、消费kafka消息
    使用idea搭建springBoot项目
    linux 虚拟机不能启动不了系统,虚拟机更改linux初始启动5,出现无法启动现象
    vwware workstation虚机网络配置NAT
  • 原文地址:https://www.cnblogs.com/liemng/p/5955169.html
Copyright © 2011-2022 走看看