Using the factory design pattern with Kotlin language
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.
Taking a look at the UML we will be implementing. ๐
The UML diagram will look as follows
Planning ๐
We need to convert the following UML into actual code, so lets split the work into tasks.
- Create the virus interface
- Create concrete virus classes that implement the
Virus
interface - Create an enumeration which will hold virus types (constants)
- Create the
VirusFactory
which will eventually generate a properVirus
given the virus type from the enumeration - 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...")
}
}
๐ก 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...")
}
}
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
}
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
}
}
}
๐ก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()
}
๐ก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.
interface Virus {
public fun mutate()
public fun spread() {
println("Spreading the virus...")
}
}
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...")
}
}
class VirusFactory {
fun makeVirus(type: VirusType): Virus? {
return when(type) {
VirusType.CORONA_VIRUS -> CoronaVirus()
VirusType.INFLUENZA -> InfluenzaVirus()
VirusType.HIV -> HIVVirus()
else -> null
}
}
}
enum class VirusType { CORONA_VIRUS, INFLUENZA, HIV }
fun main() {
val factory = VirusFactory()
val virus = factory.makeVirus(VirusType.CORONA_VIRUS)
virus?.spread()
virus?.mutate()
}