开发架构 "MVC""MVP"
平时开发中经常使用 MVC 开发架构模式,对于 MVP ,MVVP 架构模式也常听于耳,工作业余时间简单梳理其之前的逻辑关系:
MVC 架构
Model:实体模型(JavaBean);
View : 对应布局文件;
Controllor: 对应Activity业务逻辑,数据处理和UI处理;
MVP 架构「业务逻辑在Presenter」
MVC 模式使得 Activity 承担功能较多,代码量大,MVP 是其进化架构模式
Model:实体模型(JavaBean);
View:xml 与 Activity 负责View绘制与用户交互;
Presenter:负责完成View与Model之间交互与业务逻辑;
MVP 登录代码结构:
1. Model 代码 User
public class User {
private String userName;
private String password;
public User(String userName, String password) {
this.userName = userName;
this.password = password;
}
... ignore getter & setter ...
}
2. View 层代码
① 提取 ILoginView 接口代码如下:
public interface ILoginView {
void onCLearText();
void onLoginResult(Boolean result,int code);
}
② ILoginView 的实现类也就是我们的 LoginActivity
public class LoginActivity extends AppCompatActivity
implements View.OnClickListener, ILoginView {
private Button mLoginBtn;
private Button mClearBtn;
private EditText mUserName;
private EditText mPassword;
private ILoginPresenter mLoginPresenter;
private static final String TAG = "LoginActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoginBtn = findViewById(R.id.login_btn);
mClearBtn = findViewById(R.id.clear_btn);
mUserName = findViewById(R.id.user_name_edit);
mPassword = findViewById(R.id.password_edit);
mLoginBtn.setOnClickListener(this);
mClearBtn.setOnClickListener(this);
mLoginPresenter = new LoginPrisenter(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_btn:
mLoginPresenter.doLogin(mUserName.getText().toString(),mPassword.getText().toString());
break;
case R.id.clear_btn:
mLoginPresenter.clear();
break;
default:
break;
}
}
@Override
public void onCLearText() {
mUserName.setText("");
mPassword.setText("");
}
@Override
public void onLoginResult(Boolean result, int code) {
if(result){
Log.d(TAG, "onLoginResult: success");
Toast.makeText(this,"Login Success!",Toast.LENGTH_LONG).show();
}else {
Log.d(TAG, "onLoginResult: failed");
Toast.makeText(this,"Login Failed!",Toast.LENGTH_LONG).show();
}
}
}
3. Presenter代码
Presenter 业务逻辑抽象 ILoginPresenter 接口代码
public interface ILoginPresenter {
public void clear();
public void doLogin(String name, String password);
}
Presenter 实现类方法:
public class LoginPrisenter implements ILoginPresenter {
private static final String TAG = "LoginPrisenter";
private ILoginView mLoginView;
private User mUser;
public LoginPrisenter(ILoginView view) {
mLoginView = view;
mUser = new User("Liu","12345678");
}
@Override
public void clear() {
mLoginView.onCLearText();
}
@Override
public void doLogin(String username, String password) {
Log.d(TAG, "userName: "+username +"; password: "+password);
boolean result = false;
int code =0;
if (username.equals(mUser.getUserName()) && password.equals(mUser.getPassword())){
result = true;
code =1;
}else {
result = false;
code =0;
}
mLoginView.onLoginResult(result,code);
}
}