DEV Community

Cover image for Using the factory design pattern with Kotlin
Dimitrios Filippou
Dimitrios Filippou

Posted on

Using the factory design pattern with Kotlin

Introduction πŸ”₯

We all know design patterns or at least heard of them once in our lives as developers, they are supposed to ensure the maintenance integrity of our codebase and reduce headaches, but do they? The truth is, there are cases where you do not need this pattern and those cases may vary from not using an OOP language, writing a project where you don't really care about its scalability, or it's not complex enough to use a design pattern. In this article, we will get our hands dirty with Kotlin coding as well as UML & some hot tips!

Prerequisite β˜•οΈ

Before proceeding, you need to be familiar with UML, some basic Kotlin knowledge and have an idea of how Java handles inheritance.

Quick note before reading πŸ“–

Since it's 2020 and we're all quarantined, I used an example that is relevant to 2020's pandemic 🦠. We are going to make a virus factory, that creates virus Java objects! I know this is not 100% practical, but. it's fun.

This article can also be found on my blog archive which is located here https://jimfilippou.github.io/blog/using-the-factory-design-pattern-with-kotlin.

Taking a look at the UML we will be implementing. πŸ‘€

The UML diagram will look as follows

Alt Text

Planning πŸ“

We need to convert the following UML into actual code, so lets split the work into tasks.

  1. Create the virus interface
  2. Create concrete virus classes that implement the Virus interface
  3. Create an enumeration which will hold virus types (constants)
  4. Create the VirusFactory which will eventually generate a proper Virus given the virus type from the enumeration
  5. Use what we made

implementing βš’

1. Creating the virus interface

The following code will do the trick to make this Interface πŸ‘‡



interface Virus {
    public fun mutate()
    public fun spread() {
        println("Spreading the virus...")
    }
}


Enter fullscreen mode Exit fullscreen mode

πŸ’‘ TIP: Notice that in regular java interfaces, typically you only do declarations, not implementations. The function body is 100% optional because in the future it is supposed to be overridden.

The following statement comes from the documentation:

Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. They can have properties but these need to be abstract or to provide accessor implementations.

2. Creating concrete virus classes

Now we need to create the different classes that implement the Virus Interface.

πŸ’‘TIP: You can create as many classes as you wish, as long they implement the Virus interface. Typically, this pattern is more useful when you have lots of classes because when you only have a few, you can work around this issue and maybe avoid using this pattern.



class CoronaVirus: Virus {
    override fun mutate() {
        println("Mutating the corona virus...")
    }
}

class InfluenzaVirus: Virus {
    override fun mutate() {
        println("Mutating the flu virus...")
    }
}

class HIVVirus: Virus {
    override fun mutate() {
        println("Mutating the HIV virus...")
    }
}


Enter fullscreen mode Exit fullscreen mode

3. Creating the enumeration

In kotlin, it's fairly easy to make an enum by using the following code πŸ‘‡



enum class VirusType {
    CORONA_VIRUS, INFLUENZA, HIV
}


Enter fullscreen mode Exit fullscreen mode

But why do we use constants this way? couldn't we just use strings for virus types?

The answer is yes however, a good practice is not to use strings because strings are more error-prone because as humans, we tend to make typos very frequently.

If you are coming from the front-end world, the same reason applies to Redux action types βš›

4. Creating the factory 🏭

Now let's implement the VirusFactory class πŸš€



class VirusFactory {
    fun makeVirus(type: VirusType): Virus? {
        return when(type) {
            VirusType.CORONA_VIRUS -> CoronaVirus()
            VirusType.INFLUENZA -> InfluenzaVirus()
            VirusType.HIV -> HIVVirus()
            else -> null
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

πŸ’‘TIP: The return type is Virus? which means it may return null. We did this because we want to make sure that the factory accepts only the specified virus types inside the when keyword. The when keyword is just like the switch keyword, but much sexier πŸ‘.

5. Using the factory 🏭

Now that everything is completed, let's use the factory we just created!



fun main() {
    val factory = VirusFactory()
    val virus = factory.makeVirus(VirusType.CORONA_VIRUS)
    virus?.spread()
    virus?.mutate()
}


Enter fullscreen mode Exit fullscreen mode

πŸ’‘TIP: Notice that we called the functions mutate and spread with a question mark before accessing the object's properties and/or methods. This question mark means that the functions will only be called when the virus object is not NULL.

If you are familiar with JavaScript, this behaves just like optional chaining

Thank you for reading! πŸŽ‰

You reached the end! I hope you learned something. In case you need the entire codebase, I have embedded it below so you can copy and paste it. Let me know in the comments on what you think about this post or this design pattern in general.

Top comments (2)

Collapse
 
dds861 profile image
Daniyar Nurgaliyev

Another suggestion:

enum class VirusType {
CORONA_VIRUS,
INFLUENZA,
HIV;

companion object {
    fun makeVirus(type: VirusType): Virus? {
        return when (type) {
            VirusType.CORONA_VIRUS -> CoronaVirus()
            VirusType.INFLUENZA -> InfluenzaVirus()
            VirusType.HIV -> HIVVirus()
            else -> null
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

}

THEN delete VirusFactory.

and call from Main:

fun main() {
VirusType.makeVirus(VirusType.CORONA_VIRUS)?.apply {
spread()
mutate()
}
}

Collapse
 
dds861 profile image
Daniyar Nurgaliyev

Thanks for article ;)
Suggestion:
how about changing "class VirusFactory" to "object VirusFactory"? :)