Android 应用程序架构 - 建议的模型是什么?
以同样的方式,网络或桌面应用程序可能具有三层或 n 层——例如 UI、业务、数据——Android 应用程序的建议结构是什么?你如何将类分组在一起,你有哪些层等等?
In the same way a web or desktop app might have three or n tiers - UI, Business, Data for example - what is the suggested structure for an Android application? How do you group classes together, what layers do you have etc?
我刚刚开始使用 Android 开发(一个必须响应传入通知的基于互联网的应用程序)并且对我所针对的结构没有真正的感觉.建议表示赞赏.
I'm just starting Android dev (an internet-based app that must respond to incoming notifications) and have no real feel for the structure I'm aiming at. Suggestions appreciated.
从服务器端背景开始,我已经在 Android 上工作了 9 个月,其中完整的单元测试和分层架构很常见并且运行良好.
I've been working on Android for 9 months now from a server-side background where full unit testing and layered architectures are common and work well.
经过大量的反复试验,我强烈建议使用 Model View Presenter
模式,而不是 Model View Controller.
Through lots of trial and error and I would strongly suggest using the Model View Presenter
pattern, not Model View Controller.
我发现的一个大问题是 Activities
/Fragments
的生命周期不在您的控制范围内,可能会导致意外问题.
A huge issue I've found is that Activities
/Fragments
have a lifecycle which is outside your control and can lead to unexpected issues.
例如,我们的主要 Android 应用希望在平板电脑上以横向模式使用.我们在 OnCreateView()
或 OnCreate()
中执行此操作.
For example, our main android app wants to be used in landscape mode on tablets. We do this in OnCreateView()
or OnCreate()
.
在 Nexus 7 上,默认视图是纵向的,所以它以纵向模式启动 Activity,然后我们的代码说转到横向,android 最终创建了 3 次 activity
类!
On a Nexus 7, the default view is portrait so what happens is that it starts the activity in portrait mode, our code then says go to landscape and android ultimately creates the activity
class 3 times!
我们已经将网络请求连接到 onCreate
并且在这种情况下它们最终发生了 3 次.
We've hooked up network requests to onCreate
and they end up happening 3 times in this case.
当然,我们可以添加逻辑来查找重复调用,但在我看来,在架构上尝试将 UI 与业务逻辑分开会更好.
Sure, we can add logic to look for duplicate calls but, in my opinion, it would be better, architecturally to try and divide the UI from the business logic.
我的建议是使用工厂模式从活动创建演示者,但确保工厂只返回相同的实例.然后,演示者可以包含执行网络请求、查找重复项并返回缓存结果和一般业务逻辑的逻辑.
My recommendation would be to use the factory pattern to create presenters from the activity but make sure the factory only ever returns the same instance. The presenter can then contain logic to do network request, look for duplicates and return cached results and general business logic.
当网络调用的结果返回时,要么将活动发布到诸如 Otto 之类的总线(在 onResume()
上注册事件,并在 onPause()
期间取消注册)) 已注册,或确保活动实现的回调接口已更新到演示者中的最后一个活动.
When results from network calls return, either post to a bus such as Otto which the activity (register for the event on onResume()
and deregister during onPause()
) has registered to, or make sure the callback interface implemented by the activity has been updated to the last activity in the presenter.
这样,presenter
下方的代码是可单元测试的,而不依赖于片状 UI 层测试.
This way, code in the presenter
downwards is unit testable and not reliant on flaky UI layer testing.