In a recent blog post Klaas Pieter Annema wrote about using the builder pattern in Objective-C. Inspired by his post I created two categories that bring similar functionality to NSURL and NSDate.
An example:
1 2 3 4 5 |
|
My builder categories on NSDate and NSURL are available on github for review. Let me know what you think.
Background
Originating from Java the builder pattern is used to create new objects using a dedicated ‘builder’ object, instead of having every parameter in the constructor.
This pattern actually also currently exists in Objective-C Foundation. NSDate
has NSDateComponents
and as I recently wrote iOS 7 / Mavericks added NSURLComponents to complement NSURL
. Both dates and URLs are immutable objects in Foundation with only simple initializers. To have more control over their creation you use their builder objects.
Klaas Pieter actually expands on the builder pattern and shows a very elegant way of using builders in Objective-C initializers using blocks. Illustrated using his pizza example:
1 2 3 4 5 |
|
turns into
1 2 3 4 5 |
|
Perfect for application on the existing builder objects in Foundation in my opinion.