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 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 pricinple is simple, All the objects should be created in a sub classes and they all implement specific function that we define in an Interface.

All the sub classes should implement the the interface, so that ever class will have same methods.

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

ICurrency Interface:

ICurrency interafce provide two funtions symbol and code, The classes which implement this Interface must provide 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 implemenatation for tehe methods, similar to this we have another class called UnitedStatesDollar

enum class Country :

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


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

currency() function :

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

For exmaple, when we choose Spain, Greece the Euro object will be created, but if we choose UnitedStates then UnitedStatesDollar() Object will be cerated. This not just creates the Objects but also retuns 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 main function we call the currency() fucntion 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

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)
}			

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
 
Join My Facebook Group
Join Group
 
aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group