Design Patterns in Android with Kotlin

  • Code reusability: By following the Design Pattern, you can make your code reusable i.e. for performing a certain task at more than one place, you need not write the same code again and again at various places.
  • Cleaner code: You can make your code cleaner by decoupling the code and it will make the code easier to understand by using Design Pattern.

What is a Design Pattern?

As Wikipedia says:

  • Structural Pattern
  • Behavioural Pattern

Creational Pattern

The Creational Pattern is used to create some object without showing the logic or the steps that are involved in creating the object. So, every time you want an object, you need not instantiate the object by using the new operator. So, this makes the creation of object easier and can be easily created again and again. Some of the examples of Creational Pattern are Builder, Singleton, and Dependency Injection.

class Laptop(builder: Builder) {
private val processor: String = builder.processor
private val ram: String = builder.ram
private val battery: String = builder.battery
private val screenSize: String = builder.screenSize
// Builder class
class Builder(processor: String) {
var processor: String = processor // this is necessary
// optional features
var ram: String = "2GB"
var battery: String = "5000MAH"
var screenSize: String = "15inch"
fun setRam(ram: String): Builder {
this.ram = ram
return this
}
fun setBattery(battery: String): Builder {
this.battery = battery
return this
}
fun setScreenSize(screenSize: String): Builder {
this.screenSize = screenSize
return this
}
fun create(): Laptop {
return Laptop(this)
}
}
}
Laptop.Builder("i7") // processor is compulsory
.setRam("8GB") // this is optional
.setBattery("6000MAH") // this is optional
.create()
AlertDialog.Builder(this)
.setTitle("This is a title")
.setMessage("This is some message")
.show()
object DataManager{
init {
println("Singleton class invoked.")
}
fun getUserData(): User{
// some code
}
}
// to user singleton class
fun main(args: Array<String>) {
DataManager.getUserData()
// more code
}
class DataManager {
private val databaseHelper: DatabaseHelper = DatabaseHelper() // dependent on DatabaseHelper
private val networkHelper: NetworkHelper = NetworkHelper() // dependent on NetworkHelper

fun someTask() {
// do some operation with DatabaseHelper and NetworkHelper
}
}
val dataManager: DataManager = DataManager()
dataManager.someTask()
class DataManager(databaseHelper: DatabaseHelper, networkHelper: NetworkHelper) {
private val databaseHelper: DatabaseHelper = databaseHelper
private val networkHelper: NetworkHelper = networkHelper
fun someTask() {
// do some operation with DatabaseHelper and NetworkHelper
}
}
val databaseHelper: DatabaseHelper = DatabaseHelper()
val networkHelper: NetworkHelper = NetworkHelper()
val dataManager: DataManager = DataManager(databaseHelper, networkHelper)
dataManager.someTask()

Structural Pattern

In this Design Pattern, we are concerned about the structure of the code. Here we follow some particular structural pattern that will help in understanding the code and the working of code just by looking at the structure of the code. Some of the common Structural Pattern used are Adapter, Bridge, Facade, Proxy, etc.

interface FlightDetailAdapter {
// get price in indian rupees
fun getPriceInINR()

// get time in Indian Standard Time
fun getTimeInIST()
}
class AirIndiaFlightDetailsAdapter: FlightDetailAdapter {    // some AirIndiaApi that gives the time and price according to Indian standards
var api:AirIndianApi = AirIndiaAPI()
override fun getPriceInINR(): Int {
// returns the price in INR
return api.price
}
override fun getTimeInIST(): String {
//returns the time in IST
return api.time
}
}
class UnitedAirlinesFlightDetailAdapter: FlightDetailAdapter {
// some UnitedAirlinesAPI that gives the time and price according to American standards
var api:UnitedAirlinesAPI = UnitedAirlinesAPI()
override fun getPriceInINR(): Int {
// returns the price in INR
return convertUSDToINR(api.price)
}
override fun getTimeInIST(): String {
//returns the time in IST
return convertESTToIST(api.time)
}
fun convertUSDToINR(price: Int): Int {
// some logic
}
fun convertESTToIST(time: String): String {
// some logic
}
}
class FlightView(context: Context) : View(context) {
// showing flight details according to Indian time and price
fun showFlightData(fda: FlightDetailAdapter) {
priceTextView.text = fda.getPriceInINR()
timeTextView.text = fda.getTimeInIST()
}
}
val flightView: FlightView = FlightView()// for showing AirIndia flight details
flightView.showFlightData(AirIndiaFlightDetailsAdapter())
val flightView: FlightView = FlightView()// for showing UnitedAirlines flight details
flightView.showFlightData(UnitedAirlinesFlightDetailAdapter())

Behavioural Pattern

Behavioural Pattern mainly tells how the objects of the classes will communicate with each other. These patterns help us in understanding the code in a better way because by viewing the code we can identify the pattern and then we can understand the code in a better way. Some of the behavioural patterns are Chain of Responsibility, Interpreter, Mediator, Observer, Command, Model View Controler, Model View ViewModel, etc.

  • View: It is the user interface that a user sees. In Android, the user interface is built with the help of XML. So, all the views that the user sees come under this category.
  • Controller: A controller is simply a communication medium between the Model and the View. It takes the user input from the view. It processes the request and it sends the data from the Model to the view.
  • View: It is the user interface that a user sees. In Android, the user interface is built with the help of XML. So, all the views that the user sees come under this category.
  • Presenter: The presenter is responsible for giving the data to the view. If view demands some data from the Model, then it is the presenter that will fetch the data from the Model and provide the data to the view to display the required details.
  • View: It is the user interface that a user sees. In Android, the user interface is built with the help of XML. So, all the views that the user sees come under this category.
  • ViewModel: It is a bridge between the Model and the View. Here most of the user interface logic is stored. This is mainly used to store and manage the UI-related and it resolves one of the biggest problems of data loss that was faced due to screen rotation.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store