MVP模式&简单实例

来源:互联网 发布:php curl exec 不输出 编辑:程序博客网 时间:2024/05/02 10:31

网上关于什么是MVP模式的文章,一搜一大堆。这里也不班门弄斧了。

MVP要素

在MVP模式里通常包含4个要素:
(1)View:负责绘制UI元素、与用户进行交互(在Android中体现为Activity或者Fragment);
(2)View interface:需要View实现的接口,View通过View interface与Presenter进行交互,降低耦合,方便进行单元测试;
(3)Model:负责存储、检索、操纵数据(有时也实现一个Model interface用来降低耦合);
(4)Presenter:作为View与Model交互的中间纽带,处理与用户交互的负责逻辑。

MVP与MVC的区别

这里写图片描述

实例

Model

public class Model {    //方法模型层    public String model(String a, String b) {        return a + b;    }}

在这个类里定义一个model方法个模型,在app的多个地方都会调用到该方法。一般来说该方法涉及到http网络请求与大量数据传输。如:Volley框架中的http请求。

View interface

public interface MainView {    //视图层,数据传递    void setView(String a);}

接口实现该类的主要目的是降低app的耦合。setView(String a)方法用于与Presenter层交互,传递Presenter中调用Model中模型方法后产生的数据。

Presenter

public class MainPresenter {     //交互层    private Model model = new Model();//实例化,调用方法模型    private MainView mainView;    public MainPresenter(MainView mainView) {        this.mainView = mainView;    }    public void presenter(String a) {        String s = model.model("hello", a);        mainView.setView(s);    }}

实现该类作为View与Model交互中间纽带,个人感觉有点像自定义Adapter时的构造方法。
Model中的方法在这里调用,然后通过View层的setView(String a)调用Model方法处理后的结果传递到View。

View

public class MainActivity extends AppCompatActivity implements MainView {    private TextView tv;    private MainPresenter presenter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv = (TextView) findViewById(R.id.tv);        presenter = new MainPresenter(this);        presenter.presenter("world!");    }    @Override    public void setView(String a) {        tv.setText(a);    }}
//activity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    tools:context="com.mvpdemo.MainActivity">    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20dp" /></LinearLayout>

实例化Presenter作为activity中数据处理的入口。使用implements实现一个View接口,重写View interface中的方法,参数作为Presenter层传递来的数据。
这里写图片描述

优点&缺点

优点

1.降低代码的耦合性。模块之间联系越紧密,其耦合性就越强,模块的独立性则越差,模块间耦合的高低取决于模块间接口的复杂性,调用的方式以及传递的信息。
2.使代码的更加的整洁,逻辑更加清晰,代码的维护和修改更加简便。
3.将工作分解,从而进行专业化分工合作;能减少变更时各层之间的影响。
4.能简化自动化测试用例的编写等。

缺点

1.要掌握好度,对于十分简单的功能,也要分的稀碎,就有点过度设计之嫌了。
2.增加app的体积,代码量增多,一个activity多写三个类。

总结

MVP从来都不是救命稻草,只能锦上添花,不能雪中送炭。权衡利弊之后,再去选择MVP是否适合当前的项目。

demo地址:
http://download.csdn.net/detail/demonliuhui/9792639

0 0
原创粉丝点击