美文网首页
MVC,MVP,MVVM

MVC,MVP,MVVM

作者: 痰里有毒1893 | 来源:发表于2017-07-17 00:52 被阅读0次

MVC

  • Model :数据操作
  • View :视图显示
  • Controller:交互和数据之间的控制业务

优点:代码总量相对较少,适合功能简单的场景
缺点:耦合度高,Activity定位尴尬,既是V又是C

MVP

  • Model :数据操作
  • 持有bean对象
  • 包含对bean操作的各种方法: 数据库读写,网络请求
  • View :视图显示
    • 持有P层的引用
    • 包含人机交互的入口方法: onClick, onKeyDown
  • Presenter :交互和数据之间的控制业务
    • 持有M和V的引用
    • 包含对应Model需要的业务方法

优点:耦合度低,职责清晰,便于测试
缺点:接口和类较多

MVP案例-局域网udp通信

分析:
  • V层:持有P层引用,接收用户操作,向用户显示数据
  • M层:持有Bean,完成对Bean的发送和接收
  • P层:持有V层和M层引用,完成业务逻辑
工程结构
MVPDemo结构图
Demo界面
界面截图
UML接口图
UML

MVVM

875437-9e57c017aa88a959.png
  • View: 对应于Activity和xml,负责View的绘制以及与用户交互
  • Model: 实体模型
  • ViewModel: 负责完成View于Model间的交互,负责业务逻辑(DataBinding)

Databinding

Google在2015年IO 大会上推出的 Data Binding 库,主要用于更加方便的实现MVVM模型

DataBinding基本使用

  • gradle配置:
    dataBinding {
        enabled = true
    }
  • xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
</layout>
<data>
        <variable
            name="user"
            type="com.xgimi.mvvmdemo.User"/>
 </data>
<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.name}" />
  • bean
  • 继承BaseObservable
  • 对需要绑定的属性增加@Bindable注解
  • 在需要进行数据更新的方法中使用notifyPropertyChanged(int)方法进行更新
public class User extends BaseObservable{

    @Bindable
    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;

    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }
}
  • xml中其他用法:
    三目运算:
<TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@{user.name != null ? user.name : user.defaultName}" />

引入静态类:

public class MyUtil {
    public static String checkUserName(String name) {
        if (name.length() <= 1) {
            return "too short";
        } else {
            return name;
        }
    }
}
<TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@{MyUtil.checkUserName(user.name)}"/>

使用View属性:

<import type="android.view.View"/>
<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:visibility="@{user.isAdult ? View.visiable : View.gone}"
     android:text="@{user.name != null ? user.name : user.defaultName}" />

双向绑定:

<import type="com.xgimi.presenter.MyPresenter"/>
<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:onClick="@{MyPresenter.onBtnClick}"
/>

相关文章

网友评论

      本文标题:MVC,MVP,MVVM

      本文链接:https://www.haomeiwen.com/subject/feizhxtx.html