Abstract Factory Method Pattern

-- by Vikram

The reason why we don't get these concepts in the first go is that in most of the tutorial or book we jump to the solution or we keep using an age old pizza example that just doesn't let us understand the practical importance of this design pattern.

Let's say you are building a cross platform UI library for Android and iOS, both of these libraries are supposed to have buttons, switches and cards but you want to keep the aesthetics specific to the platform i.e. the Android button should look in a specific way and iOS button should look in a specific way.

You never know those who will use your library are going to use Android version or iOS version or both. To the best developer experience you would want to give something like this to the users of your library.

Android.getButton()  //Renders button specific to Android platform
 iOS.getButton()          //Renders button specific to iOS platform

Isn't it looking quite obvious choice, many of us would say yes, what if two different team-members wrote the code for Android and iOS part? There is a chance that someone would have written

newButton()  //For any one of the above?

And if you ship your library with two different methods, you will not only frustrate the user but also will have to explicitly mention all of these inconsistencies in your documentation. To solve such problems, enforce that there is a common interface for creating new UI elements (Button, Card, Switches) you can define an interface and each of your Android and iOS library must implement it.

Yes, that's all is an Abstract Factory Pattern is all about, each UI element knows for itself how to build it's object either directly or via Factory depending upon the requirements.