通过应用软件架构模式开发 android 应用程序始终是开发人员的首选。架构模式为项目文件提供了模块化,并确保所有代码都包含在单元测试中。它使开发人员可以轻松地维护软件并在未来扩展应用程序的功能。 MVP(Model-View-Presenter)和Model-View-ViewModel(MVVM)是开发者中最受业界认可的两种Android架构。
模型 — 视图 — 演示者 (MVP) 模式
MVP 架构模式提供了一种构建项目代码的简单方法。 MVP 被广泛接受的原因是它提供了模块化、可测试性以及更干净和可维护的代码库。它由以下三个部分组成:
- 模型:用于存储数据的层。它负责处理域逻辑(现实世界的业务规则)以及与数据库和网络层的通信。
- 视图: UI(用户界面)层。它提供数据的可视化并跟踪用户的操作以通知演示者。
- Presenter:从模型中获取数据并应用 UI 逻辑来决定要显示的内容。它管理视图的状态并根据用户从视图输入的通知采取行动。
模型 — 视图 — 视图模型 (MVVM) 模式
MVVM 模式与 MVP(Model — View — Presenter) 设计模式有一些相似之处,因为ViewModel扮演Presenter角色。然而,MVP 模式的弊端已经被 MVVM 解决了。它建议将数据呈现逻辑(视图或 UI)与应用程序的核心业务逻辑部分分开。 MVVM 的独立代码层是:
- Model:这一层负责数据源的抽象。 Model 和 ViewModel 协同工作以获取和保存数据。
- View:这一层的目的是通知 ViewModel 用户的操作。该层观察 ViewModel,不包含任何类型的应用程序逻辑。
- ViewModel:它公开那些与视图相关的数据流。此外,它充当模型和视图之间的链接。
MVP 和 MVVM 设计模式的区别
MVP(Model View Presenter) |
MVVM(Model View ViewModel) |
---|---|
It resolves the problem of having a dependent View by using Presenter as a communication channel between Model and View. | This architecture pattern is more event-driven as it uses data binding and thus makes easy separation of core business logic from the View. |
The one-to-one relationship exists between the Presenter and the View. | Multiple View can be mapped with single ViewModel. |
The Presenter has knowledge about the View. | ViewModel has no reference to the View. |
Model layer returns the response of the user’s input to the Presenter which forwards it to View. | After performing operations according to the user’s input, the Model layer returns the response to the View. |
Presenter handles the application flow and the View is the actual application. | ViewModel is the actual application and View is the interface for the user in order to interact with the app. |
The project file will contain more classes as well as code. | The Project file will contain more classes but less code per class. |
Ideal for simple and complex applications. | Not ideal for small scale projects. |
Easy to carry out Unit testing but a tight bond of View and Presenter can make it slightly difficult. | Unit testability is highest in this architecture. |
想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!