Android advanced MVP architecture

Write in front

My friends, it’s been two days since I missed you! I haven't had time to update in these two days, because I am studying the MVP architecture of Android recently. I think this is also an important Android advanced technology point.

Yesterday I also asked a friend around me. I asked him, "Do you know what architecture we learn about Android?" He told me dumbfounded, "Don't tell me, I really don't know the architecture of Android." He is not a novice. He has learned Android for a year. He is a small partner who has learned from Android basics with me back then. Then I briefly talked to him through the architecture of the past few days, and he suddenly realized at that time.

This shows a situation, if you don't actively learn and understand these Android-related technical points, you will always be slowly eliminated. This little friend of mine is probably not eliminated, haha, I am here to point him!

I made full use of the spare time of these two days, and through the study of documents and blogs, I thoroughly understood the structure of the MVP architecture. Then I did it again with the MVP architecture for the project at hand, which is considered a pit.

Readers who followed me from the beginning of the official account know that I will not write articles for the sake of posting articles. If there is really no technical article worth sharing at hand, I will not just write one to deal with the past. From my personal writing experience, it can be concluded that an article that is truly valuable and allows others to learn truly nutritious techniques is at least necessary from drafting to conception, to summary and finishing, and finally typesetting until it is successfully shared on the official account. More than two hours is not even enough. I once did an experiment, and completed a technical article quickly in one hour. The readers often didn't get the results, and the reading volume was bleak. The reader's mind was just a general framework for this technical point. If the reader really wants to use the shoulders of the article to climb up, this still has very strict requirements on the author of the article. Although there are more people doing official accounts, as Zhang Ge said, high-quality articles are still few. Blindly insist on posting every day, do you consider the quality of the article? Not much nonsense, go directly to the MVP architecture, and let you understand what you say today.

Android advanced MVP architecture
text

Before introducing the MVP architecture, let’s take a brief look at the MVC architecture. M "Model layer" V "View layer" C "Control layer". The MVC architecture is an architecture that is very suitable for beginners to get started. It is used for Servlet background services. Now the company basically uses the ssm framework for development. There is not much in-depth introduction to MVC here. If you want to know, there are many documents on the Internet for reference and learning. In Android, the MVC architecture is not commonly used, nor is it suitable for use. Because the code of the View view layer and the Control control layer are implemented in the entire Activity, it cannot clearly show the separation of the functions to be processed by the View layer and the Control control layer. Therefore, our Android further improves the MVC, which has evolved into the commonly used MVP architecture M "Model layer" V "View layer" P "Presenter layer" Presenter translated in English is the meaning of the representative. What role does he play in the MVP architecture? Its role is to connect the View layer and the Model layer. To put it bluntly, he is a telephone line that maintains communication at both ends. Another difference between MVP and MVC is that the Model layer and the View layer cannot communicate directly, but only through the connection of this Presenter line. What about the previous MVC? You can’t think of the Control layer as a telephone line, but as a class of processing logic. The View layer, the Control layer, and the Model layer can communicate with each other. The data transmission between the three can be very random. limit. Looking back at the MVP architecture, the data of the Model layer and the View layer will be passed to the Presenter layer for both processing. It doesn't matter if you don't understand it so far, it will be explained in detail below.

Let's look at a set of diagrams:

MVC structure diagram:

Android advanced MVP architecture

MVP structure diagram

Android advanced MVP architecture

Is the distinction between the two architectures one step clearer?

Some friends are in a hurry, brothers, stop talking nonsense, just go to the code, don't talk about these concepts. The above concepts are to form a general framework in your mind. Only when you have a basic understanding of the MVP structure will you have a clear understanding of the examples to be cited below.

Use the MVP framework to write an example of user login!

Step 1: Directory distribution of packages

List:

Android advanced MVP architecture
Sub-category:

Android advanced MVP architecture

Step 2: Model layer

The User class is a bean, which is a data class:


 1public class User {
 2    private String username ;
 3    private String password ;
 4    public String getUsername() {
 5        return username;
 6    }
 7    public void setUsername(String username) {
 8        this.username = username;
 9    }
10    public String getPassword() {
11        return password;
12    }
13    public void setPassword(String password) {
14        this.password = password;
15    }
16}

IOnLoginListener is the interface of "judge whether the login is successful":

1public interface IOnLoginListener {
2    //登录成功
3    void loginSuccess(User user);
4    //登录失败
5    void loginFailed();
6}

IUserImp is the interface of the login function:


1public interface IUserImp {
2    //登录
3    public void login(String username, String password, IOnLoginListener loginListener);
4}

UserImp is the implementation class of IUserImp interface:


 1public class UserImp implements IUserImp {
 2    @Override
 3    public void login(final String username, final String password, final IOnLoginListener loginListener) {
 4        //模拟子线程耗时操作
 5        new Thread() {
 6            @Override
 7            public void run() {
 8                try {
 9                    Thread.sleep(2000);
10                } catch (InterruptedException e) {
11                    e.printStackTrace();
12                }
13                //模拟登录成功
14                if ("zhy".equals(username) && "123".equals(password)) {
15                    User user = new User();
16                    user.setUsername(username);
17                    user.setPassword(password);
18                    loginListener.loginSuccess(user);
19                } else {
20                    loginListener.loginFailed();
21                }
22            }
23        }.start();
24    }
25}

Step 3: View view layer

The IUserLoginView in the View is the method interface that realizes the interaction with the UI:


 1public interface IUserLoginView {
 2    //View获取用户名和密码
 3    String getUserName();
 4    String getPassword();
 5    //清除用户名和密码
 6    void clearUserName();
 7    void clearPassword();
 8    //耗时提示ProgressBar
 9    void showLoading();
10    void hideLoading();
11    //提醒 登录成功失败
12    void toMainActivity(User user);
13    void showFailedError();
14}

Step 4: Presenter layer

The role in the Persenter class to connect the View layer and the Model layer:


 1public class UserLoginPresenter {
 2    private IUserImp userBiz;
 3    private IUserLoginView userLoginView;
 4    private Handler mHandler = new Handler();
 5    public UserLoginPresenter(IUserLoginView userLoginView) {
 6        this.userLoginView = userLoginView;
 7        this.userBiz = new UserImp();
 8    }
 9    public void login() {
10        userLoginView.showLoading();
11        userBiz.login(userLoginView.getUserName(), userLoginView.getPassword(), new IOnLoginListener() {
12            @Override
13            public void loginSuccess(final User user) {
14                //需要在UI线程执行
15                mHandler.post(new Runnable() {
16                    @Override
17                    public void run() {
18                        userLoginView.toMainActivity(user);
19                        userLoginView.hideLoading();
20                    }
21                });
22            }
23            @Override
24            public void loginFailed() {
25                //需要在UI线程执行
26                mHandler.post(new Runnable() {
27                    @Override
28                    public void run() {
29                        userLoginView.showFailedError();
30                        userLoginView.hideLoading();
31                    }
32                });
33            }
34        });
35    }
36    public void clear() {
37        userLoginView.clearUserName();
38        userLoginView.clearPassword();
39    }
40}

Step 5: LoginActivity to implement the login function


 1public class UserLoginActivity extends Activity implements IUserLoginView{
 2    private EditText mEtUsername,mEtPassword;
 3    private Button mBtnClear,mBtnLogin;
 4    private ProgressBar mPbLoading;
 5    private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
 6    @Override
 7    protected void onCreate(@Nullable Bundle savedInstanceState) {
 8        super.onCreate(savedInstanceState);
 9        setContentView(R.layout.activity_main);
10        initViews();
11    }
12    private void initViews()
13    {
14        mEtUsername = (EditText) findViewById(R.id.id_et_username);
15        mEtPassword = (EditText) findViewById(R.id.id_et_password);
16        mBtnClear = (Button) findViewById(R.id.id_btn_clear);
17        mBtnLogin = (Button) findViewById(R.id.id_btn_login);
18        mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
19        //登录
20        mBtnLogin.setOnClickListener(new View.OnClickListener() {
21            @Override
22            public void onClick(View v) {
23                mUserLoginPresenter.login();
24            }
25        });
26        //取消登录
27        mBtnClear.setOnClickListener(new View.OnClickListener() {
28            @Override
29            public void onClick(View v) {
30                mUserLoginPresenter.clear();
31            }
32        });
33    }
34    @Override
35    public String getUserName() {
36        return mEtUsername.getText().toString();
37    }
38    @Override
39    public String getPassword() {
40        return mEtPassword.getText().toString();
41    }
42    @Override
43    public void clearUserName() {
44        mEtUsername.setText("");
45    }
46    @Override
47    public void clearPassword() {
48        mEtPassword.setText("");
49    }
50    @Override
51    public void showLoading() {
52        mPbLoading.setVisibility(View.GONE);
53    }
54    @Override
55    public void hideLoading() {
56        mPbLoading.setVisibility(View.VISIBLE);
57    }
58    @Override
59    public void toMainActivity(User user) {
60        Toast.makeText(this, user.getUsername() +
61                " login success , to MainActivity", Toast.LENGTH_SHORT).show();
62    }
63    @Override
64    public void showFailedError() {
65        Toast.makeText(this,
66                "login failed", Toast.LENGTH_SHORT).show();
67    }
68}

When I was learning this architecture, I was a little confused. Various implementations of your interfaces made me feel dizzy. I have been watching and pondering, and I believe I will see it in the end. These efforts and dedication finally made me thoroughly understand this structure called MVP. I provide you with a good way to debug through breakpoints and follow the program step by step, so that it is easy to understand the logic and flow of the entire architecture.

Through the series of studies above, some friends will ask, how does a simple login system increase the amount of code? That's right, the amount of code has increased. Do you feel that the logical structure of the project is much clearer? Moreover, each class in each architecture layer has to perform the prescribed tasks "View The view layer is mainly responsible for interacting with the UI interface (such as: listening to user button events); the Model model layer is mainly for managing data objects; Presenter The layer mainly manages the data communication between Model and View and processes logical operations. This kind of architecture does not have advantages for small projects. When the company develops large-scale projects in the future, the amount of code is tens of thousands, and the advantages of the MVP architecture are clearly displayed, and it includes the maintenance of the later projects. The advantage is much better than writing the code into an Activity. For example, the company's project needs to add a function. According to the usual practice, first clarify the logic in the entire Activity. When you clarify the logic, it is estimated that the company's daylily is cold. However, with the MVP architecture, you can accurately find the interface that implements the function, add the method to it at will, find the implementation class that implements the method, and then implement the function. Only when you really do it can you realize the benefits of this architecture. Just listen to me saying that bb has no soft use.

Well, I have mainly learned about the MVP architecture in these two days. If there are any shortcomings, I will leave a message in the background and I will add later.

postscript

In order to update the dry goods for everyone today, most of these are summarized in the morning class. It's really not easy to make a dry article. From the beginning of the article to the public account, you are still unbelief. I calculated it took three and a half hours to update this article. There are also fewer and fewer high-quality articles on the official account, all for the benefit of updating low-quality articles without hesitation. Mutual promotion of interests and blind forwarding have almost become a normal state. I hope that my official account will always be able to output dry goods of such high quality. Through my own understanding, summary, analysis, reflection and consideration, I strive to create a unique and pure official account.

Guess you like

Origin blog.51cto.com/15064450/2602798