...

/

Abstract Factory Design Pattern

Abstract Factory Design Pattern

Learn the Abstract Factory design pattern in Kotlin and how it wraps multiple Factory Methods.

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.

Press + to interact
Abstract factory design pattern
Abstract factory design pattern

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: 8080
environment: production
Configuration file for a server with port 8080 and production environment

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: String
val value: Any
}
Property interface with name and value properties

Instead of a data class, we’ll return an interface:

interface ServerConfiguration {
val properties: List<Property>
}
Interface for server configuration with a list of properties

Then, we can provide basic implementations to be used later:

data class PropertyImpl(
override val name: String,
override val value: Any
) : Property
data class ServerConfigurationImpl(
override val properties: List<Property>
) : ServerConfiguration
Data classes for Property and ServerConfiguration interfaces implementations

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 ...