Exploring more suitable MVP model architecture design

http://www.kuqin.com/shuoit/20150814/347567.html

Regarding MVP and android, I have to say that this blog has come very late. I wanted to write this blog a long time ago. I have always been lazy, so I won't make excuses for being lazy for so long. Although this article po came out relatively late, but some programmers and friends I have contacted, everyone has only recently started to hear about mvp, and has not really been applied to the project.

At the end of 2014, there were more and more thoughts about the architecture of android on the major android forums and blogs. I have been paying attention to it. I also started to imitate and write at the end of 2014. In fact, mvp is not a new architecture. All of them are win developers who have been doing cs mode applications for many years, and wpf developers have broken things. There is no need to say anything about the concept of mvp, everyone should have read it many times, and talk about it is nonsense.

So let's now come to what design pattern everyone used before we were not exposed to mvp. At the beginning, although many people like to say that their project is MVC, but then again, what, where, why. What is MVC, where is the controller in your project, where is the view, and why do you need to use the MVC design pattern.

The 3w questioning method that everyone likes to use in various books in the history of programming. Have you seen it? This time I also installed a good B, hahaha.

1.what is MVC?
Mvc is a design pattern. Most web projects adopt the design pattern architecture of mvc, thinkphp, asp.net, and the latest razor engine. Almost everyone can say very clearly about the detailed cv relationship, so there is no need to go into details.
2. Where is mvc in your project explain to me?
This one. . . Most people answer like this: Activity fragment is the view, and model is the javabean parsed by my json, right. But what about the controller? wocao, there seems to be no controller.
3. Why should I use mvc design pattern?
Ordinary people can't tell this question clearly, and many people answer it. This is necessary for the project. This is the code specification and so on. It's useless. Anyway, he didn't think it was right. This question generally comes down to the learning and application of design patterns. After using some design patterns and comparing them, you will know why design patterns are needed, why design patterns are used, and what is the meaning of design patterns? Just one sentence: In order to reduce the degree of code coupling. What increases readability depends on your usual code style. Design patterns will improve readability a bit, but this may not be the main meaning of existence.


Well, the 3W question is over.




My summary is: 14 years ago, most of the android development was using their own so-called MVC, but most people could not find the ctroller, because the ctroller and the view were together, from two aspects, this kind of code Disadvantages:
1. This is not a true MVC mode.
2. The purpose of the design mode is to decouple, so it will definitely warn of code coupling.

In thinkphp, every request is an action, and every action finally points to a controller, but there is no request in android. There are actions in android, but the concept of action and web action
are two concepts. In the android source code, there are still some mvc, such as adapter is a kind of controller.
View is act, frag, model, so it goes without saying.
And the architecture you used before 2014 is like this, just a few BaseActivity, BaseFrag, like this, this is the factory model.

Ask how? For Android's own api and act life cycle, is it really appropriate for us to use mvc? Not suitable, to be exact, then, which design patterns are more suitable for client-side development? It is mvvm, mvp is suitable. Please see the next paragraph: the

topic back to the "WHY" question, why do we want to use design patterns? Is it to pretend to be B? No, we are in order to reduce code coupling. In summary, we can get: It doesn't matter what the design pattern uses, as long as it suits you, don't forget your original intentions for pretending, hahaha, use a bit of vocabulary. . . That is to say, whether you use MVC, MVP, MVVM, or a streamlined version of mvvm, or a streamlined version of MVP will do, the purpose of decoupling is achieved and the development time is saved the most. It’s just like Google’s official recommendation that we give up the getter setter method, but directly access the field through the point attribute. Using the getter setter method is a little slower than using the point attribute to get the field. Although it’s only a little bit, but the loop will be repeated many times. And the speed of a few seconds is affected. Give up the original java writing method and use the android method to write the code. Let go, CPU time is always more important than your code habits.


Returning to the title of the article, let’s talk about MVP. We’ve had enough of writing the view and controller together. Some pages are very big. I wrote a page. The company does not have a product manager. The page is determined entirely by UI. Fuck, I have to sit on the same page of WeChat Pay, Alipay Payment and other complicated judgments, lift up the payment client to finish the process, call back, and there are some callback channels, etc., and callbacks. Status judgment, shit, just these, the code is tiring enough, there are other data display judgments, a lot of network requests, too many codes and too complicated, right, caocaocaocao.
Therefore, mvp is better. For the specific mvp standard code pattern and structure, please go to other blogs by yourself. My blog does not want to pull some concepts that other blogs have mentioned many times, and the relationship between the view presenter does not want to be repeated. This can only increase The number of words in my blog is only.

So the question is, are there any disadvantages to mvp? 
If you are a siege lion, you have to be objective when you look at things. If you are a programmer, you don’t need to be objective. Don’t think people admire him, but you adore it. You must face up to the shortcomings of this thing. After I wrote dozens of standardized mvp application pages, I still find this product very troublesome. Although the code structure is very clear, the development time is too long and I am tired.
Summary: The advantage of mvp is to make the code organization clear, but the disadvantage is to reduce development efficiency.
In terms of how to understand the quality of programming ability, my understanding of programming is to solve problems, and the speed and elegance of problem solving represent a person's programming ability.


How to ensure that the structure of the code is clear without reducing the development speed? Recall which of the design patterns we have learned and used before is to speed up development efficiency, and are they suitable for this kind of page? It seems that the factory model is like this. The factory model is like a factory. The production efficiency is so high and so fast that you can't think of it. But it seems that mvp's standard writing is not well applied. The view of caocaocao and android is that act is different from other platforms. You can't control when the page is released. The combination of activity base classes does not seem to be a good combination. Presenter is It can be mass-produced, and I don’t want to define a presenter field in act every time, which is strange. Then this is difficult. . . . .

It has been studied for a long time to reduce the degree of mvp standardization. This can be considered. After all, the purpose of the design pattern is to reduce the degree of coupling, not for pretense. It is not necessary to strictly abide by mvp. It can reduce the degree of mvp standardization to accelerate development. But the perfect combination of factory production methods is not very good.
In the entanglement afterwards, I have time to look at some foreign framework construction methods. Finally, I found a special mvp experience under the github of a siege lion of the United States. Among them, he has a few lines of code for me Discover the knack for solving the problem.
I post my final finalized sample code below:

1. Here is MainActivity,

  1. publicclassMainActvityextendsBaseCommActivity<MainPresenter>implementsIMainView
  2. {
  3. @ViewInject(R.id.lay_main)
  4. Viewlay_main;//A layout in android itself is not used for some calculations, so there is no need to prompt the type like str_title in the naming. Whether it is RelativeLayout or LinearLayout, it is generally only used for clicking, so all names start with lay regardless of the type
  5. @Override
  6. protectedClass<MainPresenter>getPsClass(){
  7. returnMainPresenter.class;
  8. }
  9. @Override
  10. protectedintgetLayoutId(){
  11. returnR.layout.activity_main;
  12. }
  13. @Override
  14. protectedvoidinitAllWidget(){
  15. lay_main.setOnClickListener(this);
  16. }
  17. @Override
  18. protectedvoidclickView(Viewv)
  19. {
  20. switch(v.getId()){
  21. caseR.id.lay_main:
  22. {
  23. showMsg();
  24. }break;
  25. }
  26. }
  27.  
  28. @Override
  29. publicvoidshowMsg(){//测试
  30. toast("isshowmsgmethon");
  31. }
  32. }
 

2.请看IMainView

  1. publicinterfaceIMainViewextendsIBaseCommView{
  2. //在原有IBaseView的初上加一个方法要求MainActivity必须重载这个方法
  3. publicvoidshowMsg();
  4. }


3.MainPresenter

  1. publicclassMainPresenterextendsBaseCommPresenter{
  2. //请求
  3. privatestaticfinalintREQ_GETAPPLIST_MSG=0x002123;
  4. privatestaticfinalintRES_GETAPPLIST_MSG=0x002124;
  5. privatefinalStringSOFT_JP_FLAG="soft_jp_flag";
  6. privatestaticfinalStringCURRENT_PAGE="current_page";
  7. privatestaticfinalStringPAGE="page_size";
  8. privatestaticfinalStringSOFT_TYPE="soft_type";
  9. @Override
  10. publicvoidhandMsg(Messagemsg){
  11. switch(msg.what){
  12. caseREQ_GETAPPLIST_MSG:{
  13. MainRequestreq=newMainRequest();
  14. req.put(SOFT_JP_FLAG,2+"");
  15. req.put(SOFT_TYPE,1+"");
  16. req.put("soft_jh_type",0+"");
  17. Stringmac=WifiUtil.getMacAddress(iView.getActivity());
  18. req.put(CURRENT_PAGE,1+"");
  19. req.put(PAGE,10+"");
  20. req.put("mac",mac);
  21. req.setResPonseMsgWhat(RES_GETAPPLIST_MSG);
  22. sendHttpPost(req,MainResponse.class);
  23. iView.showProgressBar();
  24. }
  25. break;
  26. caseRES_GETAPPLIST_MSG:
  27. {
  28. iView.hideProgressBar();
  29. if(msg.objinstanceofMainResponse)
  30. {
  31. MainResponseres=(MainResponse)msg.obj;
  32. if(res.isSuc()){
  33. AppMainModelmainModel=res.getData();
  34. iView.toast(mainModel.data.size()+"");
  35. }
  36. else{
  37. iView.toast(res.getMsg());
  38. }
  39. }
  40. }
  41. break;
  42. }
  43. }
  44. @Override
  45. publicvoidinitData(BundlesaveInstnce){
  46. getHandler().sendEmptyMessage(REQ_GETAPPLIST_MSG);
  47. }
  48. }

可以看代码 activity中没有MainPresenter这个字段,只是在getPsClass() 的时候返回的Presenter的类型,这个getPsClass() 的调用是在activity的基类里面写的,在基类中实例化了presenter,实例化之后,presenter会执行绑定IView,IView就是this了,基类的act在基类里的消息机制的处理方法直接传递到了presenter中执行了,所以,这样写Mainactivity写的代码就超级少了。管理都在基类里面了。这种写法真的好爽!哈哈哈!

presenter应该负责一些逻辑处理,这是毋庸置疑,但是 有些逻辑又需要activity的参与,这也会带来的问题事 有些逻辑是放在activity好还是presenter好,那么我们犹豫该放在哪里的时候,只需要根据一点判断,act是 view,frag是view,他应该只是负责一些控件,presenter是管理者,他就不要直接去管理view,这样子很多东西就想通了。

但是android比较特别的是act,frag都有自己的生命周期,这就是android特别的地方,跟做网站后台的区别就拉开了,具体生命周期内的一些操作,就要看你的个人喜好去分配了。

如果你也在研究mvp的更好的方式,更好的使结构更清晰,更加加快开发速度,那你看下我的代码,找下是否有你需要,来解决你的一些困惑,我也是才疏学浅,希望大家多多指点相互学习。 或许MVVM在数据绑定这块比mvp更适合,但是 mvp的自由行很大有些细节还是需要你自己的去推敲,别人说的再好也只是说个概念罢了。

代码地址: http://code.taobao.org/svn/frame_mvp/

代码挂到了 taocode上面, 用svn检出即可,我的github上不是这个框架,是我改版的另外一个老外的mvp框架。

PS:最后补充几句,其实设计模式你玩的再好也只是达到了解耦的目的,但是代码的可读性的问题还是需要你业余多多学习下好的写代码方式,不要明明都是 button1 button2 ,写switch case 1 case 2 case3 回头来看你的btn 看你的case 23456789 鬼知道你表达什么意思,你个SB。多去分析下哪些开源的框架,既能懂得原理,学到知识,还能学习到好的代码风格。 就像 你看我的代码没在view presenter中解析服务器返回的json一样,我都写在数据请求里面了,服务器本身返回的就应该做到很标准,做到你不需要判断全都可以转model ,转java bean,这才是好的服务器开发人员。 view 和 presenter应该做他应该做的事情,不应该去负责json解析的这种事情,我的swich case 也没用123456,而是用常量代替, 我不需要去为每一个case写注释,也可以清晰的看到这行代码就知道他表达什么意思,很多代码风格还是要去仔细推敲。 我不多说了。

Guess you like

Origin blog.csdn.net/kerwinJu/article/details/53131407