架构思考之MVC、MVP、谷歌架构组件

MVC  -> MVP系列(主流)-> 2017 Google I/O Android 架构组件1.0 稳定版

https://github.com/googlesamples/android-architecture

1、MVC

(图片源于网络)

      我们知道,在Android中,View(XML)的作用是很弱的,因此Activity/Fragment既充当了View的角色,又充当了Controler的角色,且View和Model之间存在交互,这导致一个问题:在项目比较大的情况下,Activity/Fragment中的代码迅速增加,一个Activity/Fragment文件中的代码可能就好几千行。

2、MVP

(图片源于网络)

      为了减轻Activity/Fragment的负担,切断View和Model之间的联系,MVP模式应运而生。Presenter将业务逻辑部分的代码抽离出来,View只负责显示。各层之间通过接口交互。Google在其github上也提供了许多MVP及MVP-XXX模式的Demo,鼓励开发者使用MVP。虽然相对于MVC,MVP已经解决了Activity/Fragment臃肿的问题,但是项目达到一定的规模就会发现产生太多的接口文件,且Presenter也可能面对自身臃肿的问题。

3、Google大礼包

2017 Google I/O 大会,不仅确立了Kotlin为安卓开发的官方语言,还有一个细节,发布了谷歌官方Android 应用架构库。

核心思想:观察者模式;

核心类:LifeCycle

ViewModelLiveData是可感知生命周期的组件。DataBinding实现ViewModel的双向绑定。Room是操作SQLite的原生ORM框架。

3.1、概览


      ViewModel、LiveData、Room等都是Google为我们提供的组件支持,DataBinding虽然在此图未体现,但也是Google直接支持的双向数据绑定组件。
Model bean( 实体类 ) DataSource Http 请求相 关、数据库相关);
View xml View Activity Fragment UI 相关;
ViewModel :可以理解为 Controler
-----------------------------------------------------------------------
ViewModel需要数据就向Repository要,ViewModel不管数据源的具体细节,ViewModel只负责业务逻辑处理,ViewModel不持有任何UI控件的引用,因此通知界面代码进行更新操作的重任就交给了LiveData了。
LiveData也是一个能够感知生命周期的组件,LiveData会在Activity/Fragment处于active的时候,通知界面代码更新,否则不通知。界面代码进行更新UI操作的时候,此时就可以使用DataBinding了。

3.2、LifeCycle

Lifecycle是一个抽象类,该类保存了有关组件(Activity/Fragment)生命周期状态的信息, 并且允许其他对象观察此状态。目前,生命周期管理(lifeCycles)同时也已集成到支持库中(Support Library)。

注意:lifecycles 就是处理UI界面的生命周期,在26版本以后(>26)的Support库中,AppCompatActivity和Fragment中都实现了LifecycleOwner,内部已经对UI界面的生命周期做了处理了。LifecycleOwner中只有一个方法getLifeCycle(),该方法返回LifeCycle实例。

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
}

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());

3.3、ViewModel



1、ViewModel与Lifecycle绑定,使用者无需担心生命周期。
2、ViewModel将视图的数据和逻辑从具有生命周期特性的实体(如 Activity 和 Fragment)中剥离开来。
3、ViewModel不持有任何UI控件或Activity的引用,也不会被也不会被configuration change影响。比如旋转屏幕后Activity会重新create,这时候使用ViewModel可以轻松缓存使用之前的数据,开发者无需再次请求网络调用数据。
因此可以很方便在多个组件之间分享数据。
->数据的更新如何通知到View层?这就要仰仗LiveData。
示例:
public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // Do an asyncronous operation to fetch users.
    }
}
public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        // Create a ViewModel the first time the system calls an activity's onCreate() method.
        // Re-created activities receive the same MyViewModel instance created by the first activity.

        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

3.4、LiveData

LiveData 是一款基于观察者模式的可感知生命周期的核心组件,它是一个数据持有类,持有数据并且这个数据可以被观察被监听,和其他Observer不同的是,LiveData持有界面代码Lifecycle的引用,意味着它和Lifecycle是绑定的。可以及时作出相应更新和释放。
示例:
public class NameViewModel extends ViewModel {

// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getCurrentName() {
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<String>();
        }
        return mCurrentName;
    }

// Rest of the ViewModel...
}
public class NameActivity extends AppCompatActivity {

    private NameViewModel mModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Other code to setup the activity...

        // Get the ViewModel.
        mModel = ViewModelProviders.of(this).get(NameViewModel.class);

        // Create the observer which updates the UI.
        final Observer<String> nameObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String newName) {
                // Update the UI, in this case, a TextView.
                mNameTextView.setText(newName);
            }
        };

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        mModel.getCurrentName().observe(this, nameObserver);
    }
}

可以在onChanged回调中使用DataBinding。

3.5、最终架构 - MVVM


3.6、如何引入

allprojects {
    repositories {
        jcenter()
        google()
    }
}
dependencies {
    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:1.0.0"
    annotationProcessor "android.arch.lifecycle:compiler:1.0.0"

    // Room
    implementation "android.arch.persistence.room:runtime:1.0.0"
    annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

    // Paging
    implementation "android.arch.paging:runtime:1.0.0-alpha4-1"

    // Test helpers for LiveData
    testImplementation "android.arch.core:core-testing:1.0.0"

    // Test helpers for Room
    testImplementation "android.arch.persistence.room:testing:1.0.0"
}
要求:Android Studio 3.0、Gradle 4
学习资料:谷歌开发者(中国)
https://developer.android.google.cn/develop/index.html

4、其他技术更新学习

1、新的一级开发语言Kotlin;
2、RxJava2、Glide4;
3、运行时权限变化(8.0、7.0);
4、Dagger2;
5、Support Libaray V26,新增可自动调节大小的TextView、Emoji(TextView、
Button、EditText)、可以像访问其他资源一样访问字体文件(res/font)、基于物
理的动画;
6、阿里
阿里规约插件;
阿里巴巴Java开发手册;
阿里巴巴热修复手册;
7、Google
Google 推出的三大变更:
 a)从2018年下半年开始,强制要求 targetSdkVersion(Google Play);
 b)2019年8月前支持64位的Android架构;
 c)在2018年初为APK添加安全性元数据;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值