Factory Method
The Factory Method is all about creating objects. But why do we need a method to create objects? Isn't it what constructors are all about?
Well, constructors have their inherent limitations, which we're about to discuss.
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?
Let's say we...