The Abstract Factory
Here it comes, with a little delay, but I was tired with 10 hours drive from Lithuania 🇱🇹 after the weekend. I will experiment also with convention so future posts can be as juicy as possible. 🍉
Sometimes we need our applications or its parts to be as flexible as Houdini. Either we use various solutions to solve one problem or we need to run certain tasks in different environments, The Abstract Factory is the pattern we should look into. And the crucial thing to remember is that the code does not know which implementation is using.
It is really simple. As always there are key actors in this pattern. Here they are:
Abstract Factory is an interface to create products, it could be simple protocol.
Concrete Factory is implementation of abstract protocol like ProductionServicesFactory or StagingServicesFactory.
Abstract Product is an interface(protocol) that is returned from create methods, WebService and DatabaseService.
Concrete Product is an implementation of Abstract Product interface and I used plenty of them in each Concrete Factory.
Client uses only abstract interfaces we have created, in our case it will be MainFlowController.
And voila. Now based for example on DEBUG flag we can run different services when needed. It is really easy to add another one like TestServicesFactory. And we can use it right out of the box.
So let me say a few more words on The Abstract Factory pattern. It does some things well but is bad in others. First of all it Isolates Implementation so it helps control objects created by our app. Clients always use them throughout the Abstract Interface. It is also very easy to implement a new functionality as we create another implementation of AppServicesFactory and 🎉. We can use it in whole app 😀, no sweat! But it actually makes one thing harder. If we ever need another Product like for example LoginService, then we have to add its handling everywhere. And that could be quite a lot of code in advanced projects.