Android开发技巧(使用MVP模式)
一、MVP介绍</span>
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 ; } }