Skip to content

安卓数据层框架浅析

这两天在思考远程资源框架重构的思路,刚好看到安卓的框架指南,记个学习笔记

安卓框架指南

  • 原文

    A typical Android app contains multiple app components, including activitiesfragmentsservicescontent providers, and broadcast receivers. You declare most of these app components in your app manifest. The Android OS then uses this file to decide how to integrate your app into the device's overall user experience. Given that a typical Android app might contain multiple components and that users often interact with multiple apps in a short period of time, apps need to adapt to different kinds of user-driven workflows and tasks.

    Keep in mind that mobile devices are also resource-constrained, so at any time, the operating system might kill some app processes to make room for new ones.

    Given the conditions of this environment, it's possible for your app components to be launched individually and out-of-order, and the operating system or user can destroy them at any time. Because these events aren't under your control, you shouldn't store or keep in memory any application data or state in your app components, and your app components shouldn't depend on each other.

简单来讲,对于安卓系统来说,应用程序组件可能会单独无序启动,操作系统或者用户可以随时销毁这些组件并且不受我们开发者的控制,所以我们不应该在应用程序组件中存储或记忆任何应用程序数据或状态,并且应用程序组件不应该相互依赖

通用架构原则

在安卓中,状态或数据通常从层次结构的较高作用域类型流向较低作用域类型,事件通常从较低作用域类型触发,直到它们到达相应数据类型的SSOT,例如,应用程序数据通常从数据源流向用户界面。按钮按下等用户事件从用户界面流向应用程序数据被修改并以不可变类型公开的SSOT。

其实总结起来有点像java swing的设计思路,本质上还是UI与底层逻辑分离,每个应用程序应该至少有两层

  • 在屏幕上显示应用程序数据的UI层 • The UI layer that displays application data on the screen.
  • 包含应用的业务逻辑并公开应用程序数据的数据层 • The data layer that contains the business logic of your app and exposes application data.

只不过安卓框架这里加入了一个领域层作为附加层来简化和重用UI和数据层之间的交互

Tip:我们在日常 Java Swing开发中也不建议将数据和UI耦合在一起,新设计器为了解决这一问题付出了很多精力去重构,同时也不建议将耗时业务逻辑冻结在EDT中,而是用swingworker包一下,这些其实都是在提倡将具体的业务逻辑与UI分离开

Untitled

数据层

UI层我这边不做过多解析,对我来说比较重要的是数据层的设计,在安卓中比较常见的数据层架构是通过Repository来实现的

Untitled

注意这里有个误区,我一直以为安卓的Repository和DDD的仓储模式是一个东西,但是就官方给出的架构和代码来看,安卓的repository还没有达到领域模型的那个抽象地步,这边更像只是简单抽出来一层新的与数据源交互的Repository层次,并没涉及到具体的贫血模型到充血模型的转换,这个地方其实也有一些文章在诟病(eg: https://proandroiddev.com/the-real-repository-pattern-in-android-efba8662b754),但是我觉得具体的Repository使用还是得看具体的应用场景,如果只是简单的安卓应用组件,确实没必要直接上DDD

数据层的负责内容

Repository classes are responsible for the following tasks:

存储库类负责以下任务:

  • Exposing data to the rest of the app.
    • 将数据暴露给应用程序的其余部分。
  • Centralizing changes to the data.
    • 集中对数据的更改。
  • Resolving conflicts between multiple data sources.
    • 解决多个数据源之间的冲突。
  • Abstracting sources of data from the rest of the app.
    • 从应用程序的其余部分抽象数据源。
  • Containing business logic.
    • 包含业务逻辑。

每个数据源类都应该负责只使用一个数据源,可以是文件、网络源或本地数据库,数据源类是应用程序和系统之间进行数据操作的网桥。

java
class ExampleRepository(
    private val exampleRemoteDataSource: ExampleRemoteDataSource, // network
    private val exampleLocalDataSource: ExampleLocalDataSource // database
) { /* ... */ }

更多具体内容可以直接看官方文档

https://developer.android.com/topic/architecture/data-layer

最后更新于: