Design Patterns: The Factory
If you guys are fans of the Harry Potter series, you will remember Tom Riddle’s diary which had a lot of tricks to make the magic work. Well, design patterns are similar except over here, patterns are solutions to general problems you come across in your daily life and Tom Riddle is, well you know, devs like you and me.
As a tribute, design patterns were first introduced by a group called Gang-Of-Four who published a book called Design Patterns: Elements of Reusable Object-Oriented Software. You can find more details here.
So basically Design Patterns answer one simple question — What to do when you are in this situation! Or better put, what not to do in such situations. Lol.
There are 23 patterns which are categorized into Creational, Structural and Behavioral which basically stand for How to create, How to inherit, and How to communicate respectively.
The Factory Pattern
The Factory pattern gets it’s name from obviously a factory. Its called so, because a factory is comprised of many different tools and spare parts. These are used to construct products as and when required. You get an order to make a car, you use the tools and parts to make a car, you get an order to make a boat, well you get the idea.
Look at this diagram, where the user tells the factory to give him a circle.
We have an interface called Shape which has a function to be implemented called draw(). We then have 3 separate classes which implement the interface’s function - drawing the shape accordingly. We then have a Factory class that takes a parameter and returns an object as required. So if you tell the factory class to return a circle, it will return a circle object and so on.
A popular Use-Case: To better understand this, say you are developing the home-page of your mobile application which has several different sections. Say a section shows all the recent posts, another section shows all the trending images and yet another one shows all the upcoming birthdays.
One approach is to hard code this into your code so that it looks the same for every user. This would mean the code is tightly coupled and you would need to release a new version for tweaking the UI.
Another approach is to make 3 classes RecentPosts, TrendingImages and Birthdays. And a factory class that calls the particular object based on the parameter it gets. This way, all you have to do is send parameters from the server and the app will create objects and display them on the home page. You have a fully customizable homepage which you can setup differently for different users thus giving a better experience. You can even play around with it and hide some important information from users whom you don’t like :D
Let me know in comments where else you would like to use this. Meanwhile, I will be back with the other patterns soon :D
Happy coding !