Abstract Factory Design Pattern
Learn the Abstract Factory design pattern in Kotlin and how it wraps multiple Factory Methods.
We'll cover the following...
Abstract Factory is a greatly misunderstood design pattern. It has a notorious reputation for being very complex and bizarre— but it’s actually quite simple. If we could understand the Factory Method design pattern, we’ll understand this one in no time. This is because the Abstract Factory design pattern is a factory of factories. A factory is a function or class that’s able to create other classes. In other words, an abstract factory is a class that wraps multiple factory methods.
In the real world, the Abstract Factory design pattern is often used in frameworks and libraries that get their configuration from files. The Spring Framework is just one example of these. To better understand how the design pattern works, let’s assume we have a configuration for our server written in a YAML file:
server:port: 8080environment: production
Our task is to construct objects from this configuration.
We know how to use Factory Method to construct objects from the same family. But here, we have two families of objects that are related to each other but are not siblings. First, let’s describe them as interfaces:
interface Property {val name: Stringval value: Any}
Instead of a data class, we’ll return an interface:
interface ServerConfiguration {val properties: List<Property>}
Then, we can provide basic implementations to be used later:
data class PropertyImpl(override val name: String,override val value: Any) : Propertydata class ServerConfigurationImpl(override val properties: List<Property>) : ServerConfiguration
The server configuration simply contains the list of properties—and a property is a pair comprising a name
object and a value
object.
This is the first time we’ve seen the Any
type being used. The Any
type is Kotlin’s version of Java’s object
, but with one important distinction: it cannot be ...