🏠 Simple Factory
A real world example:
Consider, you are building house and you need doors. You can either put on some carpenter clothes, bring some glue, wood, tools and make the door yourself. Or, you can call the factory and get the door delivered to you; so that you don't need to learn anything about door making or deal with the mess it brings.
In simple words,
Simple Factory generates an instance for client without exposing any instantiation logic to the clients.
Wikipedia says,
In Object oriented Programming language (OOP), Factory is an object for creating other objects.
Formally, a factory is a function or method that returns objects of a varying protoype
or class from some method call, which is assumed to be new
.
A Programatic example:
First of all, we have a door interface and implementation of a wooden door.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Then we have our door factory that makes the door and returns it.
1 2 3 4 5 6 7 |
|
And then it can be used as:
1 2 3 4 5 6 7 8 9 10 |
|
❓ When to use?
When creating an object is not just a few assignments, but involves some logic; it makes sense to put it in a dedicated factory instead of repeating same code everywhere.