MVP设计模式的应用

常常听说或是看到关于Java二十三种设计模式的研究或是介绍,但往往只是介绍了其核心思想,很少有具体实例来介绍的,所以本文就以实例介绍一下安卓MVP模式是如何应用的吧。

主要的三个类:

InforChangeActivity
InforChangeView
InforChangePresenter

一、InforChangeView

此类主要实现了页面所需相关数据的统一接口,以便于Presenter获取Activity中的数据(Activity类需要实现此接口,Presenter实例化时需要传入该接口的实例(即Activity中实现的))

public interface InforChangeView {
    public String getChangedData();
    public int getFlag();
}

二、InforChangePresenter

此类主要用来进行网络访问、数据库操作等获取数据的相关操作。此类中的方法是Activity中通过该类的对象来访问的,同时此类可以使用InforChangeView的对象访问Activity中继承接口实现的方法来获取所需提交的数据。

public class InforChangePresenter {
    private Context context;
    private InforChangeView changeView;
     ........

    /** 构造函数 */
    public InforChangePresenter(Context context, InforChangeView changeView) {
        this.context = context;
        this.changeView = changeView;
        .........
    }

    public boolean changeData() {

        // 网络或数据库操作,获取数据
        .........
        return result;
    }

    ..........
    /**
     * 提交更新的信息
     * 
     * @param uuir
     * @return
     */
    public boolean postChangeData(UserUpdateInfoReqVO uuir) {
        .........
    }
 }

三、InforChangeActivity

此类主要进行UI的更新等操作,继承View接口,使用Presenter获取及提交从UI得到的数据。

public class MyInforChangeActivity extends BaseActivity implements
        InforChangeView {

    private int flag;// 判断传入的界面
    private Intent intent;
    private boolean result;
    private InforChangePresenter inforChangePresenter;
    ........

    @ViewInject(R.id.edtTxt_myinfor_change)
    private EditText changeET;
    @ViewInject(R.id.iv_back)
    private ImageButton backBtn;
    @ViewInject(R.id.tv_finish)
    private TextView completeTV;
    @ViewInject(R.id.tv_title)
    private TextView titleTV;

    @OnClick(R.id.tv_finish)
    public void finish(View view) {
        ........
    }

    @Override
    protected void onCreate(Bundle arg0) {
        // TODO Auto-generated method stub
        super.onCreate(arg0);
        setContentView(R.layout.activity_myinfor_change);
        ViewUtils.inject(this);
        .......
        initTitle(flag);
        init();
    }

    private void init() {
        intent = new Intent();
        /** 实例化Presenter对象*/
        inforChangePresenter = new InforChangePresenter(this, this);
        ........
    }

    private void initTitle(int i) {
        ........
    }

    @Override
    public String getChangedData() {
        // TODO Auto-generated method stub
        return changeET.getText().toString().trim();
    }

    @Override
    public int getFlag() {
        // TODO Auto-generated method stub
        return this.flag;
    }
}

以上三个类即将原本全部写在Activity类中的代码分隔开来,从而实现了UI,业务逻辑,数据的分离,这样的代码更加规范便于理解,也便于工程的维护。以上或许有理解不当之处,欢迎指正!

猜你喜欢

转载自blog.csdn.net/kiddingboy_wjj/article/details/47118127