Common Design Patterns and App Architectures for Android

Discover how to make your Android code cleaner and easier to understand with these common design patterns for Android apps. “Future You” will appreciate it! By Aaqib Hussain.

4.4 (10) · 1 Review

Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

State

In the State pattern, the state of an object alters its behavior accordingly when the internal state of the object changes. Take a look at the following snippets:

// 1
interface PrinterState {
  fun print()
}

// 2
class Ready : PrinterState {
  override fun print() {
    print("Printed Successfully.")
  }
}

// 3
class NoInk : PrinterState {
  override fun print() {
    print("Printer doesn't have ink.")
  }
}

// 4
class Printer() {
  private val noInk = NoInk()
  private val ready = Ready()
  private var state: PrinterState
  private var ink = 2

  init {
    state = ready
  }

  private fun setPrinterState(state: PrinterState) {
    this.state = state
  }

  // 5
  fun startPrinting() {
    ink--
    if (ink >= 0) {
      setPrinterState(ready)
    } else {
      setPrinterState(noInk)
    }
    state.print()
  }

  // 6
  fun installInk() {
    ink = 2
    print("Ink installed.")
  }
}

Here’s a code breakdown:

  1. PrinterState defines the states of a printer.
  2. Ready is a concrete class implementing PrinterState to define a ready state of the printer.
  3. NoInk is a concrete class implementing PrinterState to define that the printer has no ink.
  4. Printer handler does all the printing.
  5. startPrinting starts printing.
  6. installInk installs ink.

Here’s how you use it:

val printing = Printer()
printing.startPrinting() // Printed Successfully.
printing.startPrinting() // Printed Successfully.
printing.startPrinting() // Printer doesn't have ink.
printing.installInk() // Ink installed.
printing.startPrinting() // Printed Successfully.    

So, you create an object of the class Printer to print. The Printer class handles all the states of the printer internally. It’s either on a Ready state or in a NoInk state.

App Architectures

“Could there ever be a requirement where I’ll have to modify or implement new features in this project?” – Future You

App architectures play a vital part in structuring a loosely coupled codebase. You can use it anywhere, irrespective of the platform. App architectures help you write easily testable, extensible and decoupled code.

In simple terms, Architecture refers to the overall organization of your code in things like:

  1. Responsibilities for each class
  2. Folder organization
  3. Structure of the code: network calls, responses, errors.

Types of App Architectures

The App Architectures used to create solid and maintainable codebases are many, but in this article you will learn the most popular ones:

  • Model View Controller
  • Model View ViewModel
  • Clean Architecture

Model View Controller

Model View Controller, or MVC, refers to one of the most popular architectural patterns and the one from which many others derive. It’s particularly easy to set your project up this way on Android. Its name refers to the three ways to classify the classes in your code:

In Kotlin we use Data classes, while in Java they were called POJOs (Plain Old Java Object).

  • Model: Your data classes. If you have User or Product objects, these model the real world.
  • View: Your visual classes. Everything the user sees falls under this category. In Android’s case it is mainly XML, although you can also make views in code and with the introduction of compose you will have other types of views.
  • Controller: The glue between the two. It updates the view, takes user input and makes changes to the model.

Dividing your code between these three categories will go a long way toward making it decoupled and reusable.

Eventually, a client will ask Future You to add a new screen to the app that uses its existing data. Following the MVC paradigm means Future You can easily re-use the same models and only change the views.

Or perhaps the client will ask Future You to move that fancy widget from the home screen to the detail screen. Separating your view logic makes this an easy task.

Additionally, moving as much layout and resource logic as possible into Android XML keeps your View layer clean and tidy. Nice!

You may have to do some drawing in Kotlin from time to time. In that case, it’ll help to separate the drawing operations from your activity and fragment classes.

Over time, you’ll find making architectural decisions easier under MVC and Future You can more easily solve issues as they arise.

Model View ViewModel

This unfortunately-quite-confusingly-named presentation architectural pattern is similar to the MVC pattern. The Model and View components are the same.

The ViewModel object is the glue between the model and view layers but operates differently than the Controller component. Instead, it exposes commands for the view and binds the view to the model. When the model updates, the corresponding views update via the data binding.

Similarly, as the user interacts with the view, the bindings work in the opposite direction to automatically update the model.

The MVVM pattern is trending upwards in popularity but is still a fairly recent addition to the pattern library. Google is now recommending this pattern as part of its Architecture Components library. Future You would love to keep your eye on this one! :]

Clean Architecture

Clean Architecture is not in itself an architecture but a concept. It describes the overall app architecture: how the various layers of an app, business objects, use cases, presenters, data storage and UI, communicate with one another. MVC and MVVM exist within Clean Architecture at the outer presentation and UI layers.

You can find the original Clean Architecture definition in this article. There are many examples of Clean Architecture for Android available, including Architecting Android…The evolution.

Where to Go From Here?

While it feels great to keep abreast of the latest flashy APIs, keeping your apps updated can quickly lead to redesign-fatigue. Investing in software design patterns and app architectures early on will improve your return on development time. You’ll start to notice you get more done with less effort.

Check out Design Pattern by Tutorials to cover all the Design patterns in detail with code samples and their applications. If you want to have a deep understanding of App Architectures, check out Advanced Android App Architecture.

You can also read timeless classics such as Design Patterns by the “Gang of Four.” Compared to Material Design or Android Wear, this book might seem ancient, but it documents many useful design patterns that predate Android itself!

I hope this article serves as a starting point for your research into common design patterns for Android! If you have any questions or comments, please join the forum discussion below. Future You would be happy if you did. :]