Design patterns in Android — All developers should know about it.

Dennis
DennisPaulMaliekal
Published in
2 min readJan 15, 2024

What is a design pattern?

  • Reusable solution for commonly occurring software design problems.
  • It is a description or a template saying how to solve the problem.
  • They are formalized best practices to solve problems.

As everyone knows there are three categories of design patterns creational, structural, and behavioral.

Builder Pattern — Creational

When we can use it or what problem it solves :

  • When the object is complex and has more parameters some of them are optional.
  • We can avoid building constructors.
  • In Kotlin named parameter can be used to solve this problem.

Rules :

  • Private constructor.
  • An inner class (Builder)
  • functions to set the value for each field.
  • build() function which returns the class
class Book private constructor(
val id: String,
val title: String,
val author: String?,
val genre: Genre?
) {

data class Builder(
val id: String,
val title: String,
var author: String? = null,
var genre: Genre? = null
) {
fun author(author: String) = apply { this.author = author }
fun genre(genre: Genre) = apply { this.genre = genre }
fun build() = Book(id, title, author, genre)
}
}

Observer Pattern — Behavioral.

Also known as Publish / Subscribe Pattern, Signal-Slot Pattern. It is used in event-driven architecture.

When we can use it or what problem it solves :

  • When a main information source provides updates and needs to share them with various interested objects.
  • If we implement a “Pull — Mechanism” to get the information from the source — it will lead to usage of too many resources.

LiveData, Kotlin Flows, RXKotlin(RXJava) everything follows an observer pattern.

Dependency Injection — design principle

Dependency Injection is a design principle (can’t be described as a design pattern) that is often used alongside design patterns to improve the overall design and maintainability of software systems.

When we can use it or what problem it solves :

  • How can a class be independent of the creation of the objects it depends on?
  • How can an application, and the objects it uses support different configurations?

When we solve the above problems we get the following advantages.

The dependency Injection design pattern implements the programming principle of Inversion of Control(IOC).

--

--