Factory

We'll start with the Factory Method formalized in the book Design Patterns by Gang of Four.

This is one of the first patterns I teach my students. They're usually very anxious about the whole concept of design patterns, since it has an aura of mystery and complexity. So, what I do is ask them the following question.

Assume you have some class declaration, for example:

class Cat {    val name = "Cat"}

Could you write a function that returns a new instance of the class? Most of them would succeed:

fun catFactory() : Cat {    return Cat()}

Check that everything works:

val c = catFactory() println(c.name) // Indeed prints "Cat"

Well, that's really simple, right?

Now, based on the argument we provide it, can this method create one of two objects? ...

Get Hands-On Design Patterns with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.