Which Architecture patterns are used on Android? [closed]
Asked Answered
F

12

284

I'm doing a small research of mobile platforms and I would like to know which design patterns are used in Android?

e.g. in iOS Model-view-controller is very widely used together with delegation and other patterns.

What patterns and where in particular does Android use?

EDIT

I'm not asking for design patterns used deep in kernel, dalvik and so on, but about patterns which an application developer will meet while developing an application.

Fireproofing answered 6/2, 2011 at 21:20 Comment(6)
Given the Android platform incorporates a Linux kernel, it's far too big a suite of software to answer this question other than 'all of the patterns named so far, and probably a few new ones if you look carefully enough'Aholah
@Pete, Ok, probably you are right, but at the same time I'm not going so deep as kernel, I'm interested in surface of application, e.g. in iOS UIViewController implemented using MVC (UIViewController is a controller and its root UIView is view), UIApplication uses delegation having Application Delegate as delegate and so on...Fireproofing
I think you should really learn Android from the bottom up and not try to "port" you knowledge from iOS to Android. There are a lot of great books out there. Apress makes a bunch. If you understand the app and service lifecycle in android you should be able to get how to desing apps properly.Cabbageworm
Magic: raywenderlich.com/109843/common-design-patterns-for-androidRabush
This might help:stackoverflow.com/a/49694378Acinus
MVC on Android: upday.github.io/blog/model-view-controllerAvast
U
328

I tried using both the model–view–controller (MVC) and model–view–presenter architectural patterns for doing android development. My findings are model–view–controller works fine, but there are a couple of "issues". It all comes down to how you perceive the Android Activity class. Is it a controller, or is it a view?

The actual Activity class doesn't extend Android's View class, but it does, however, handle displaying a window to the user and also handle the events of that window (onCreate, onPause, etc.).

This means, that when you are using an MVC pattern, your controller will actually be a pseudo view–controller. Since it is handling displaying a window to the user, with the additional view components you have added to it with setContentView, and also handling events for at least the various activity life cycle events.

In MVC, the controller is supposed to be the main entry point. Which is a bit debatable if this is the case when applying it to Android development, since the activity is the natural entry point of most applications.

Because of this, I personally find that the model–view–presenter pattern is a perfect fit for Android development. Since the view's role in this pattern is:

  • Serving as a entry point
  • Rendering components
  • Routing user events to the presenter

This allows you to implement your model like so:

View - this contains your UI components, and handles events for them.

Presenter - this will handle communication between your model and your view, look at it as a gateway to your model. Meaning, if you have a complex domain model representing, God knows what, and your view only needs a very small subset of this model, the presenters job is to query the model and then update the view. For example, if you have a model containing a paragraph of text, a headline and a word-count. But in a given view, you only need to display the headline in the view. Then the presenter will read the data needed from the model, and update the view accordingly.

Model - this should basically be your full domain model. Hopefully it will help making your domain model more "tight" as well, since you won't need special methods to deal with cases as mentioned above.

By decoupling the model from the view all together (through use of the presenter), it also becomes much more intuitive to test your model. You can have unit tests for your domain model, and unit tests for your presenters.

Try it out. I personally find it a great fit for Android development.

Uppity answered 21/7, 2011 at 3:17 Comment(5)
Great answer! I have questions though: 1. Activity = View, did I get this right? 2. Would you implement the presenter as its own public class, or as an inner class of the Activity? Or a fragment (also inner class)? 3. Do you mean that transfer classes shall be used as instead of the actual model classes in the Activity (view)?Yaya
1. Yes, I use them as views within the MVP pattern. 2. personally, I segment them into individual public classes, but this is a matter of taste I suppose :) 3. I explained this quite poorly, the sentence "forward the classes needed" is misleading. What I mean, is the presenter sits between the view and the model, it reads the model and then updates the view. I will update my answer to be a bit more clear :)Uppity
I actually really love Android development because it is highly decoupled. How I use MVC: Use Activities purely for user IO, and use a local service for all of your processing. When the service wants to show something - broadcast it to your activities! I really hate it when other dev's put way too much processing in activities.Effendi
@SomeoneSomewhere why not have a class which handles this stuff in separate thread / AsyncTasks, why a service?Willard
Please note that handling views is a job of a controller but how to get handled that only view knows.Hence i do not agree with your this statement "Activity handles displaying a window to the user and also handle the events of that window". Hence we can say that activity is a controller.Subprincipal
S
89

Update November 2018

After working and blogging about MVC and MVP in Android for several years (see the body of the answer below), I decided to capture my knowledge and understanding in a more comprehensive and easily digestible form.

So, I released a full blown video course about Android applications architecture. So, if you're interested in mastering the most advanced architectural patterns in Android development, check out this comprehensive course here.

This answer was updated in order to remain relevant as of November 2016


It looks like you are seeking for architectural patterns rather than design patterns.

Design patterns aim at describing a general "trick" that programmer might implement for handling a particular set of recurring software tasks. For example: In OOP, when there is a need for an object to notify a set of other objects about some events, the observer design pattern can be employed.

Since Android applications (and most of AOSP) are written in Java, which is object-oriented, I think you'll have a hard time looking for a single OOP design pattern which is NOT used on Android.

Architectural patterns, on the other hand, do not address particular software tasks - they aim to provide templates for software organization based on the use cases of the software component in question.

It sounds a bit complicated, but I hope an example will clarify: If some application will be used to fetch data from a remote server and present it to the user in a structured manner, then MVC might be a good candidate for consideration. Note that I said nothing about software tasks and program flow of the application - I just described it from user's point of view, and a candidate for an architectural pattern emerged.

Since you mentioned MVC in your question, I'd guess that architectural patterns is what you're looking for.

Enter image description here


Historically, there were no official guidelines by Google about applications' architectures, which (among other reasons) led to a total mess in the source code of Android apps. In fact, even today most applications that I see still do not follow OOP best practices and do not show a clear logical organization of code.

But today the situation is different - Google recently released the Data Binding library, which is fully integrated with Android Studio, and, even, rolled out a set of architecture blueprints for Android applications.

Two years ago it was very hard to find information about MVC or MVP on Android. Today, MVC, MVP and MVVM has become "buzz-words" in the Android community, and we are surrounded by countless experts which constantly try to convince us that MVx is better than MVy. In my opinion, discussing whether MVx is better than MVy is totally pointless because the terms themselves are very ambiguous - just look at the answers to this question, and you'll realize that different people can associate these abbreviations with completely different constructs.

Due to the fact that a search for a best architectural pattern for Android has officially been started, I think we are about to see several more ideas come to light. At this point, it is really impossible to predict which pattern (or patterns) will become industry standards in the future - we will need to wait and see (I guess it is matter of a year or two).

However, there is one prediction I can make with a high degree of confidence: Usage of the Data Binding library will not become an industry standard. I'm confident to say that because the Data Binding library (in its current implementation) provides short-term productivity gains and some kind of architectural guideline, but it will make the code non-maintainable in the long run. Once long-term effects of this library will surface - it will be abandoned.


Now, although we do have some sort of official guidelines and tools today, I, personally, don't think that these guidelines and tools are the best options available (and they are definitely not the only ones). In my applications I use my own implementation of an MVC architecture. It is simple, clean, readable and testable, and does not require any additional libraries.

This MVC is not just cosmetically different from others - it is based on a theory that Activities in Android are not UI Elements, which has tremendous implications on code organization.

So, if you're looking for a good architectural pattern for Android applications that follows SOLID principles, you can find a description of one in my post about MVC and MVP architectural patterns in Android.

Spoofery answered 3/6, 2015 at 19:4 Comment(3)
Well done for providing such resources! Thanks!Mesmerize
Very useful links!Fye
I like your video course! ThanksUnderdone
M
87

enter image description here

When i reach this post it really help me to understand patterns with example so i have make below table to clearly see the Design patterns & their example in Android Framework

I hope you will find it helpful.

Midships answered 18/6, 2017 at 19:3 Comment(7)
Please edit your post and show the actual content as text instead of screenshots. Others can't copy and paste from your images or help you fix your typos. See here for details. Thank you.Gault
Never post pictures of text when you can post the actual text. Be sure that it is properly formatted and readable.Take
Thank you for this answer I was so confused between architectural patters and design patterns, I have still one question what is oo-design and developement!? @Peter WalterBullfinch
I up vote this answer because although the question of @Fireproofing mentions design patterns by referencing to architectures but they are not the same. I consider this answer very informative and complementary to the original questionTappet
Event bus uses publisher and subscriber design patternConjugation
Thanks for correction Devrath, i wrote it long back.Midships
dagger 2 is not di, dagger is just annotation processor, nothing moreStaging
L
51

There are various patterns used in Android framework like:

  • Broadcast receiver uses Observer pattern
  • Remoter service invocation uses Proxy pattern
  • View and view group uses Composite pattern
  • Media framework uses Facade pattern
Lamellirostral answered 17/12, 2012 at 0:1 Comment(2)
can you please please share the links (references)Transmission
please share reference so that i can find more about it. ThanksMegrims
C
31

Here is a great article on Common Design Patterns for Android:

Creational patterns:

  • Builder (e.g. AlertDialog.Builder)
  • Dependency Injection (e.g. Dagger 2)
  • Singleton

Structural patterns:

  • Adapter (e.g. RecyclerView.Adapter)
  • Facade (e.g. Retrofit)

Behavioral patterns:

  • Command (e.g. EventBus)
  • Observer (e.g. RxAndroid)
  • Model View Controller
  • Model View ViewModel (similar to the MVC pattern above)
Cultivar answered 12/7, 2016 at 17:47 Comment(3)
Key points from the article would be nice.Shevlo
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.Columbary
Event bus uses publisher and subscriber design patternConjugation
B
20

The Following Android Classes uses Design Patterns

1) View Holder uses Singleton Design Pattern

2) Intent uses Factory Design Pattern

3) Adapter uses Adapter Design Pattern

4) Broadcast Receiver uses Observer Design Pattern

5) View uses Composite Design Pattern

6) Media FrameWork uses Façade Design Pattern

Butyrate answered 16/4, 2016 at 18:29 Comment(0)
A
11

In the Notifications case, the NotificationCompat.Builder uses Builder Pattern

like,

mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_notification)
                    .setContentTitle(getString(R.string.notification))
                    .setContentText(getString(R.string.ping))
                    .setDefaults(Notification.DEFAULT_ALL);
Arsenal answered 28/8, 2015 at 7:38 Comment(2)
This is actually the Builder pattern.Paneling
@Paneling I'm wrong. Thank you for correcting me. I thought it's a simple version of Decorator Pattern.Arsenal
A
7

Android also uses the ViewHolder design pattern.

It's used to improve performance of a ListView while scrolling it.

The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable processor cycles. Specifically, it avoids frequent calls of findViewById() during ListView scrolling, and that will make it smooth.

Abacus answered 1/3, 2015 at 3:31 Comment(0)
P
5

All these patterns, MVC, MVVM, MVP, and Presentation Model, can be applied to Android apps, but without a third-party framework, it is not easy to get well-organized structure and clean code.

MVVM is originated from PresentationModel. When we apply MVC, MVVM, and Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.

At the moment, without an third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value. What's more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical.

For these reasons, some years ago we started an open source project, RoboBinding - A data-binding Presentation Model framework for the Android platform. RoboBinding helps you write UI code that is easier to read, test, and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to the Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.

Proudman answered 27/5, 2014 at 9:16 Comment(0)
M
2

I would like to add a design pattern that has been applied in Android Framework. This is Half Sync Half Async pattern used in the Asynctask implementation. See my discussion at

https://docs.google.com/document/d/1_zihWXAwgTAdJc013-bOLUHPMrjeUBZnDuPkzMxEEj0/edit?usp=sharing

Model answered 20/12, 2013 at 6:18 Comment(0)
A
1

In Android the "work queue processor" pattern is commonly used to offload tasks from an application's main thread.

Example: The design of the IntentService class.

The IntentService receives the Intents, launch a worker thread, and stops the service as appropriate.All requests are handled on a single worker thread.

Abacus answered 7/11, 2015 at 16:40 Comment(0)
S
0

Binder uses "Observer Pattern" for Death Recipient notifications.

Shanta answered 9/8, 2016 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.