Factory Pattern in kotlin

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.

In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor.

Problems solved by Factory Method :

  • Complex object creation, especially within several layers of class hierarchy
  • Usage of the new() operator, causing complexity, duplication and inflexibility issues in application code
  • When the client is unauthorized to access in-detail class implementations

When to use Factory design pattern :

  • Factory method is used when Products don't need to know how they are created.
  • We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided
  • Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.

Code for Factory design in kotlin :

The principle is simple, All the objects should be created in a subclasses and they all implement a specific function that we define in an Interface.

All the subclasses should implement the interface so that every class will have the same methods.

In below example, we will see the currency of the country and the Symbol for that currency. We will try to do it by providing sample values

ICurrency Interface:

ICurrency interface provides two functions symbol and code, The classes which implement this Interface must provide a body for these two methods.


interface ICurrency {
    fun symbol(): String
    fun code(): String
}

Euro :

We are implementing the ICurrency interface with Euro class, so it is mandatory to provide the body to symbol() & code() functions.


class Euro : ICurrency {
    override fun symbol(): String {
        return "€"
    }
    override fun code(): String {
        return "EUR"
    }
}

We can provide any kind of implementation for the methods, similar to this we have another class called UnitedStatesDollar

enum class Country :

We have provided a list of countries to choose from, user can pick any of the country by accessing the enum class.


enum class Country {
    UnitedStates, Spain, UK, Greece
}

currency() function :

We have implemented the when construct for deciding which object to create.

For example, when we choose Spain, Greece the Euro object will be created, but if we choose UnitedStates then UnitedStatesDollar() Object will be created. This not just creates the Objects but also returns it.

If we pass any country which does not have the case in when construct then the control will be redirected to default block.


fun currency(country: Country): ICurrency? {
    when (country) {
        Country.Spain, Country.Greece -> return Euro()
        Country.UnitedStates -> return UnitedStatesDollar()
        else -> return null
    }
}

main() function :

In the main function, we call the currency() function to create the object based on the country we pass, if the result is not null then code() function will be invoked and assigned otherwise noCurrencyCode assigned

The complete code for Factory Design pattern in kotlin

interface ICurrency {
    fun symbol(): String
    fun code(): String
}

class Euro : ICurrency {
    override fun symbol(): String {
        return "€"
    }
    override fun code(): String {
        return "EUR"
    }
}

class UnitedStatesDollar : ICurrency {
    override fun symbol(): String {
        return "$"
    }
    override fun code(): String {
        return "USD"
    }
}

enum class Country {
    UnitedStates, Spain, UK, Greece
}

fun currency(country: Country): ICurrency? {
    when (country) {
        Country.Spain, Country.Greece -> return Euro()
        Country.UnitedStates -> return UnitedStatesDollar()
        else -> return null
    }
}

fun main(args: Array<String>) {
    val noCurrencyCode = "\"I am not Creative, so Currency Code Available\""

    println(currency(Country.Greece)?.code() ?: noCurrencyCode)
    println(currency(Country.Spain)?.code() ?: noCurrencyCode)
    println(currency(Country.UnitedStates)?.code() ?: noCurrencyCode)
    println(currency(Country.UK)?.code() ?: noCurrencyCode)
}			

The output of the Kotlin's Factory Design pattern


EUR
EUR
USD
"I am not Creative, so Currency Code Available"

Advantage of Factory Design Pattern :

  • Remove the code duplication using the factory class and method
  • Subclass implementations are independent of application clients, hence enforce flexibility, maintainability, and testability
  • Eliminate many run-time errors due to service delegation to the factory class
  • Maintain the code consistency through consolidating object creation mechanism within the factory class.
  • Encourage the programming to interface principle ensuring the code quality of the system
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions