Builder Design Pattern in iOS
This is a short story about the usage of Builder Design Pattern in iOS. Builder Pattern is one of the Creational Design Pattern which allows you to create and customize objects at runtime.
Use Cases
You can use Builder in order to construct part of your program’s mechanism. For instance, you can build a Game via GameBuilder.
In the above example, we create a Game via GameBuilder. All of the variables in Game object are set as private. You can’t directly modify Game object via its variables but you can use a GameBuilder to create a Game object. This approach provides you the control and privacy when writing your own APIs.
Keep in mind that you can’t change the behavior of a Game object when It is created. So the one that will be built should be immutable. Your decision here is important. You shouldn’t be able to change the behavior of the object once It’s been built. So use this pattern when you actually need it.
Real-World Usage
Big tech companies especially Google, loves to work with Builder Pattern.
In Android, you can do something like this to build the map options of your GoogleMaps instance:
Or you can use Geofencing API to create a GoogleApiClient instance:
Thinking of the iOS world, you can create a wrapper with a Builder pattern. When you want to show an ActionSheet or Alert you would do something like this:
You can simplify the above code via Builder pattern. What if we use Builder pattern to achieve this goal?
As you can see with fever lines of code we can achieve the same goal thanks to Builder pattern. The above code is an open-source project of mine called ‘EasyAction’. You can deep dive into code and check out the implementation.
Be wise when you decide to use Builder Design Pattern. It grants you to create complex objects by simplifying the implementation but It also takes away your flexibility to change the behavior of objects at runtime
Links and Code Samples
Thanks for reading!