一篇使用Clean Architecture(整洁架构)模式开发Android的详细指南

文章出处: https://medium.com/@dmilicic/a-detailed-guide-on-developing-android-apps-using-the-clean-architecture-pattern-d38d71e94029

Ever since I started developing Android apps there was this feeling that it could be done better. I’ve seen a lot of bad software design decisions during my career, some of which were my own — and Android complexity mixed with bad software design is a recipe for disaster. But it is important to learn from your mistakes and keep improving. After a lot of searching for a better way to develop apps I encountered the Clean Architecture. After applying it to Android, with some refinement and inspiration from similar projects, I decided that this approach is practical enough and worth sharing.

自从我开始开发安卓后我就有一种它能变得更好的感觉。我曾经在我的职业生涯中遇到过很多糟糕的软件设计,有一些是我自己的项目--Android的复杂性与糟糕的软件设计的结合是导致灾难的诀窍。但是从中学习到自身的错误并且不断改善是非常重要的。在经过大量搜索寻找适合开发APP的方法后,我邂逅了Clean Architecture。在把它应用到安卓上后,通过相似项目的改进和灵感,我认为这种方法实用并且值得分享。

The goal of this article is to provide a step-by-step guide for developing Android apps in a Clean way. This whole approach is how I’ve recently been building my apps for clients with great success.


What is Clean Architecture?


I will not go into too much detail here as there are articles that explain it much better than I can. But the next paragraph provides the crux of what you need to know to understand Clean.


Generally in Clean, code is separated into layers in an onion shape with one dependency rule: The inner layers should not know anything about the outer layers. Meaning that the dependencies should point inwards.


This is the previous paragraph visualized:


Clean Architecture, as mentioned in the provided articles, makes your code:
· Independent of Frameworks
· Testable.
· Independent of UI.
· Independent of Database.
· Independent of any external agency.


· 独立架构
· 可测试
· 独立UI
· 独立数据库
· 独立于任何外部结构

I will hopefully make you understand how these points are achieved with examples below. For a more detailed explanation of Clean I really recommend this article and this video.


What this means for Android


Generally, your app can have an arbitrary amount of layers but unless you have Enterprise wide business logic that you have to apply in every Android app, you will most often have 3 layers:
· Outer: Implementation layer
· Middle: Interface adapter layer
· Inner: Business logic layer


· 外层: 执行层
· 中层: 接口适配器层
· 内层: 业务逻辑层

The implementation layer is where everything framework specific happens. Framework specific code includes every line of code that is not solving the problem you set to solve, this includes all Android stuff like creating activities and fragments, sending intents, and other framework code like networking code and databases.


The purpose of the interface adapter layer is to act as a connector between your business logic and framework specific code.


The most important layer is the business logic layer. This is where you actually solve the problem you want to solve building your app. This layer does not contain any framework specific code and you should be able to run it without an emulator. This way you can have your business logic code that is easy to test, develop and maintain. That is the main benefit of the Clean Architecture.

最重要的层级是业务逻辑层。这是你实际解决构建应用程序时要解决的问题的地方。这一层级不包含任何具体框架的代码,并且你应该可以在不借助任何模拟器的情况下运行它。通过这种方式你可以得到易于测试、开发和维护的业务逻辑代码。这是Clean Architecture整洁架构的主要益处。

Each layer, above the core layer, is also responsible for converting models to lower layer models before the lower layer can use them. An inner layer can not have a reference to model class that belongs to the outer layer. However, the outer layer can use and reference models from the inner layer. Again, this is due to our dependency rule. It does create overhead but it is necessary for making sure code is decoupled between layers.


Why is this model conversion necessary? For example, your business logic models might not be appropriate for showing them to the user directly. Perhaps you need to show a combination of multiple business logic models at once. Therefore, I suggest you create a ViewModel class that makes it easier for you to display it to the UI. Then, you use a converter class in the outer layer to convert your business models to the appropriate ViewModel.


Another example might be the following: Let’s say you get a Cursor object from a ContentProvider in an outer database layer. Then the outer layer would convert it to your inner business model first, and then send it to your business logic layer to be processed.


I will add more resources to learn from at the bottom of the article. Now that we know about the basic principles of the Clean Architecture, let’s get our hands dirty with some actual code. I will show you how to build an example functionality using Clean in the next section.

我会在下面加入更多的资源以供参考。现在我们知道了一些Clean Architecture整洁架构的基本原理,让我们用实际的代码来让它更加清楚。我会在下一节中像你展示如何使用Clean构建示例功能。

How do I start writing Clean apps?


I’ve made a boilerplate project that has all of the plumbing written for you. It acts as a Clean starter pack and is designed to be built upon immediately with most common tools included from the start. You are free to download it, modify it and build your apps with it.

我已经创建了一个样板项目 ,其中包含为你编写的所有管道。它作为一个Clean的启动包,旨在立即构建并包含最常用的工具。你可以自由下载、修改并使用它构建你的应用程序。

You can find the starter project here: Android Clean Boilerplate



Getting started writing a new use case


This section will explain all the code you need to write to create a use case using the Clean approach on top of the boilerplate provided in the previous section. A use case is just some isolated functionality of the app. A use case may (e.g. on user click) or may not be started by a user.


First let’s explain the structure and terminology of this approach. This is how I build apps but it is not set in stone and you can organize it differently if you want.




The general structure for an Android app looks like this:
· Outer layer packages: UI, Storage, Network, etc.
· Middle layer packages: Presenters, Converters
· Inner layer packages: Interactors, Models, Repositories, Executor


· 外层包: UI, Storage, Network等
· 中层包: Presenters, Converters
· 内层包: Interactors, Models, Repositories, Executor

Outer layer


As already mentioned, this is where the framework details go.


UI — This is where you put all your Activities, Fragments, Adapters and other Android code related to the user interface.

UI-这是你放置你的Activities, Fragments, Adapters和其他安卓代码来和用户进行联系的地方

Storage — Database specific code that implements the interface our Interactors use for accessing data and storing data. This includes, for example, ContentProviders or ORM-s such as DBFlow.

Storage-实现Interactors用于访问数据库和存储数据接口的数据库特定代码。包括ContentProviders 或ORM-s,如 DBFlow

Network — Things like Retrofit go here.

NetWork-类似于Retrofit 运行的地方。

Middle layer


Glue code layer which connects the implementation details with your business logic.


Presenters — Presenters handle events from the UI (e.g. user click) and usually serve as callbacks from inner layers (Interactors).


Converters — Converter objects are responsible for converting inner models to outer models and vice versa.


Inner layer


The core layer contains the most high-level code. All classes here are POJOs. Classes and objects in this layer have no knowledge that they are run in an Android app and can easily be ported to any machine running JVM.


Interactors — These are the classes which actually contain your business logic code. These are run in the background and communicate events to the upper layer using callbacks. They are also called UseCases in some projects (probably a better name). It is normal to have a lot of small Interactor classes in your projects that solve specific problems. This conforms to the Single Responsibility Principleand in my opinion is easier on the brain.


Models — These are your business models that you manipulate in your business logic.


Repositories — This package only contains interfaces that the database or some other outer layer implements. These interfaces are used by Interactors to access and store data. This is also called a repository pattern.


Executor**** — This package contains code for making Interactors run in the background by using a worker thread executor. This package is generally not something you need to change.


A simple example


In this example, our use case will be: “Greet the user with a message when the app starts where that message is stored in the database.” This example will showcase how to write the following three packages needed to make the use case work:
· the presentation package
· the storage package
· the domain package


· 演示包
· 存储包
· 域包
The first two belong to the outer layer while the last one is the inner/core layer.


Presentation package is responsible for everything related to showing things on the screen — it includes the whole MVP stack (it means it also includes both the UI and Presenter packages even though they belong to different layers).