Category Kotlin

Design Patterns for Android

Model–View–Controller (MVC) Foundation

MVC Fundations
  • The original pattern for applications with a UI
  • The innovation that the pattern introduced was a guarantee that the view—what was rendered on the screen—was always consistent.

Process

  1. User, see something on the screen (the View) and, in response to what they see, take some action. They touch the screen, type something, speak, whatever. They do something that will change the state of the application.
  2. Their input is fielded by the Controller.The Controller has two responsibilities. First, it orders the user’s input. For any given user event—say, tapping the “stop” button—all other user events happen either before that tap or after it. No two events are ever processed at the same time.
  3. The Controller’s second responsibility is to translate user input into operations on a Model.
  4. The Model is the business logic of an application. It probably combines some kind of persistent data store and perhaps a network connection with rules for combining and interpreting the input from the Controller.

Android Patterns

⭐ In Android, regardless of the pattern, an Activity object, and Fragment—takes the role of the View.

In Android, regardless of the pattern, an Activity object, and Fragment—takes the role of the View.

Model–View–Intent

  • One of the oldest versions of MVC adopted by the Android community
  • The pattern decouples the Activityfrom a Model by using Intent and their payloads.
  • It can be quite slow and the code for constructing the Intents quite bulky

⛔ Deprecated for new patterns.

Model–View–Presenter

  • A goal for all of these MVC-based patterns is to loosen the coupling among the three components and to make information flow unidirectionally.
  • One of the earliest refinements replaces the View and Local Model references to each other with references to interfaces.
  • Extremely thin views and testable Presenters lead to much more robust applications.
  • The Local Model might hold no references to the View at all.
  • all.

📌 The most important attribute of this architecture, however, is that the Presenter (this architecture’s name for the Local Model) can be unit tested.

The most important attribute of this architecture, however, is that the Presenter (this architecture’s name for the Local Model) can be unit tested.

Process

  • The Local Model holds a reference, not to the View Activity, but simply to the implementation of some interface.
  • The View proxies user input events to its Presenter.
  • The Presenter, responds to the events, updating Local Model and Model state as necessary.
  • It then notifies the View that it needs to redraw itself. Because the Presenter knows exactly what changes have taken place, it may be able to request that the View update only affected sections, instead of forcing a redraw of the entire screen.

Model–View–ViewModel

  • Google, with its introduction of Jetpack, supports an architecture called Model–View–ViewModel (MVVM)
  • It is the most common and most discussed pattern for modern Android apps.
  • An Activity or a Fragment takes the role of the View
  • The View code will be as simple as it is possible to make it, often contained entirely within the Activity or Fragment subclass.
  • Complex views will need separate classes for image rendering or a RecyclerView. Even these, though, will be instantiated and installed in the view, directly by the Activityor Fragment.

📌 The feature of this pattern is that a single interface, Observable, is used to transmit changes in the state of the Local Model to the View.

Process

  • The ViewModel is responsible for wiring together the commands necessary to update the View and the backend Model.
  • Instead of the multiple Presenter interfaces used in the MVP pattern, the ViewModel represents viewable data as a collection of Observables.
  • The View simply registers as an observer for these observables and reacts to notifications of changes in the data they contain.
  • The Jetpack library calls these ObservableLiveData
  • LiveData object is an observable data holder class with a single generified interface that notifies subscribers of changes in the underlying data.

Basic Design Patterns with Kotlin

A design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Categories

GoF book presents the 3 categories of the design patterns:

  • Creational
  • Behavioral
  • Structural

How to implement the design pattern in the code?

  • Please read about the patterns, implement them along the way, read existing code, and start recognizing them (create with the frameworks and libraries you use).
  • The common mistake of developers is coming up with a ready solution for the problem and trying to fit the pattern you just learned.
  • Come up with the raw solution first, and then try to recognize the pattern use case if the implementation becomes painful.

[Behavioral] Observer

Observer pattern – defines one-to-many relationship between objects in such a way, that when the object changes his state, then all of his dependent objects are notified and updated — GoF book

Intent

Observer is a behavioral design pattern that allows creating a structure that allows objects (observers subjects or publishers) to inform about their state to change other objects (observers or subscribers or subjects) in a loosely coupled way.

Problem

  • Imagine that you have two types of objects: a Customer and a Store. The customer is very interested in a particular brand of product (say, it’s a new model of the iPhone) which should become available in the store very soon.
  • The customer could visit the store every day and check product availability. But while the product is still en route, most of these trips would be pointless.

Solution

  • The object that has some interesting state is often called subject, but since it’s also going to notify other objects about the changes to its state, we’ll call it publisher.
  • All other objects that want to track changes to the publisher’s state are called subscribers.
  • The Observer pattern suggests that you add a subscription mechanism to the publisher class so individual objects can subscribe to or unsubscribe from a stream of events coming from that publisher.

Observer solution

[Creational] Singleton

Intent

  • Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Problem

  • Ensure that a class has just a single instance. Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource—for example, a database or a file.
  • Provide a global access point to that instance. Remember those global variables used to store some essential objects? While they’re very handy, they’re also very unsafe since any code can potentially overwrite the contents of those variables and crash the app.

Solution

  • Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
  • Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.
  • Special consideration for Kotlin:
    • Kotlin’s representation of a Singleton class requires the object keyword only
    • An object class can contain properties, functions and the init method.
    • The constructor method is NOT allowed.
    • An object cannot be instantiated in the way a class is instantiated.
    • An object gets instantiated when it is used for the first time providing lazy initialization.
    • Object declaration’s initialization is thread-safe.

Singleton Example

Kotlin Essentials

History

  • Kotlin was created by the JetBrains team from St. Petersburg, Russia. JetBrains is perhaps best known for the IntelliJ Idea IDE, the basis for Android Studio. Kotlin is now used in a wide variety of environments across multiple operating systems.
  • Google announced support for Kotlin on Android. According to the Android Developers Blog, as of 2021, over 1.2 million apps in the Google Play store use Kotlin, including 80% of the top one thousand apps.

Kotlin

Docs

Conventions

Examples