在写完MVP模式(一)后,总觉得难以理解,并且感觉不应该在model层操作业务逻辑
下面同样以用户登陆为例,把model的业务实现交给Presenter操作
创建model
public class UserInfo {
public String account;
public String pwd;
}
创建view与model逻辑实现Presenter的接口
public class UserLoginApi {
//view接收结果
public interface View{
void onLoginStar();
void onLoginEnd();
void onSuccess();
void onFail();
}
//model的逻辑实现,交给Presenter
public interface Presenter {
void login();
}
}
创建Presenter实现登陆用户,并把结果返回给view
public class UserLoginPresenter implements UserLoginApi.Presenter {
private UserLoginApi.View view;
private UserInfo userInfo;
public UserLoginPresenter(UserLoginApi.View view,UserInfo userInfo){
this.view = view;
this.userInfo = userInfo;
}
@Override
public void login() {
//模拟登陆
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
view.onLoginStar();
if (TextUtils.isEmpty(userInfo.account)||TextUtils.isEmpty(userInfo.pwd)){
return;
}
int i =new Random().nextInt(1);
if (i==0){
view.onSuccess();
view.onLoginEnd();
}else {
view.onFail();
view.onLoginEnd();
}
}
},2000L);
}
}
View层
public class LoginActivity extends Activity implements UserLoginApi.View{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new UserLoginPresenter(this,new UserInfo()).login();
}
@Override
public void onLoginStar() {
}
@Override
public void onLoginEnd() {
}
@Override
public void onSuccess() {
}
@Override
public void onFail() {
}
}