MVP模式在Android开发中的应用
http://blog.csdn.net/vector_yi/article/details/24719873
一、MVP介绍
- View不直接与Model交互,而是通过与Presenter交互来与Model间接交互
- Presenter与View的交互是通过接口来进行的,更有利于添加单元测试
- 通常View与Presenter是一对一的,但复杂的View可能绑定多个Presenter来处理逻辑
- View可以与Model直接交互
- Controller是基于行为的,并且可以被多个View共享
- 可以负责决定显示哪个View
- public class UserBean {
- private String mFirstName ;
- private String mLastName ;
- public UserBean (String firstName, String lastName) {
- this .mFirstName = firstName;
- this .mLastName = lastName;
- }
- public String getFirstName() {
- return mFirstName ;
- }
- public String getLastName() {
- return mLastName ;
- }
- public interface IUserView {
- int getID();
- String getFristName();
- String getLastName();
- void setFirstName (String firstName);
- void setLastName (String lastName);
- }
- public interface IUserModel {
- void setID (int id);
- void setFirstName (String firstName);
- void setLastName (String lastName);
- int getID();
- UserBean load (int id);//通过id读取user信息,返回一个UserBean
- }
- public class UserPresenter {
- private IUserView mUserView ;
- private IUserModel mUserModel ;
- public UserPresenter (IUserView view) {
- mUserView = view;
- mUserModel = new UserModel ();
- }
- public void saveUser( int id , String firstName , String lastName) {
- mUserModel .setID (id );
- mUserModel .setFirstName (firstName );
- mUserModel .setLastName (lastName );
- }
- public void loadUser( int id ) {
- UserBean user = mUserModel .load (id );
- mUserrView .setFirstName (user .getFirstName ());//通过调用IUserView的方法来更新显示
- mUserView .setLastName (user .getLastName ());
- }
- }
- public class UserActivity extends Activity implements OnClickListener ,
- IUserView {
- private EditText mFirstNameEditText , mLastNameEditText , mIdEditText ;
- private Button mSaveButton , mLoadButton ;
- private UserPresenter mUserPresenter ;
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- switch ( v. getId()) {
- case R .id .saveButton :
- mUserPresenter .saveUser (getID (), getFristName (),
- getLastName ());
- break ;
- case R .id .loadButton :
- mUserPresenter .loadUser (getID ());
- break ;
- default :
- break ;
- }
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。