Factory pattern and DI in swift

Yessen
Deem.blogs
Published in
3 min readFeb 16, 2022

--

In my previous article I was explaining one of the ways of reducing the amount of lines in your ViewControllers and making it more readable by using Reusable UI components. But what if we want to improve our whole project structure?

One of the initial steps would be deciding on which architecture pattern to use. Some of the most popular in iOS development are MVVM, MVC, MVP and so on. However, in this article I won’t be explaining on how to implement this or that particular architectural design, but indeed I will be explaining how to improve your design by using factory pattern and Dependency Injection known as DI.

“In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.”

So let’s suppose your project is using MVVM structure, where View has instance of ViewModel, and ViewModel has instance of Model.

You would write your code like this:

MainViewController
MainViewModel

For the beginning, it looks fine! However, imagine in case of more complicated ViewModel and ViewController, where you probably will have Network Adapter connected to your ViewModel, you will have to also add

And the dependency can increase more and more. Imagine, if you will need to change some dependencies in far future as the back end requirements would change? You will have to debug every VC until you will find the one you need.

In this case Factory pattern with DI will help as a lot!

Simply saying our factory will be playing a role of the struct or class (can be protocol as well), which will create MainViewController when asked to do!

MainVCFactory

Since MainVCFactory is handling every initialization and injection of components, we can change constructors at MainVC and MainViewModel!

MainViewController
MainViewModel

The cool thing I like about this pattern is that you can organize your VCs by modules like this!

So every module will have 4 files: ViewController, ViewModel, Model, and Factory!

Finally, if you want to push or present your MainViewController from other VC, you can simply write:

let vc = MainVCFactory.make()

And done! Happy coding!

--

--