Joris Kluivers

I like to build software.

The Builder Pattern in Objective-C Foundation

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
NSURL *url = [NSURL URLWithBuilderBlock:^(NSURLComponents *builder) {
  builder.scheme = @"http";
  builder.host = @"joris.kluivers.nl";
  builder.path = @"/blog/2014/04/08/the-builder-pattern-in-objective-c/";
}];

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
PizzaBuilder *builder = [[PizzaBuilder alloc] init];
builder.size = 12;
builder.pepperoni = YES;
builder.mushrooms = YES;
Pizza *pizza = [builder build];

turns into

1
2
3
4
5
Pizza *pizza = [Pizza pizzaWithBlock:^(PizzaBuilder *builder]) {
    builder.size = 12;
    builder.pepperoni = YES;
    builder.mushrooms = YES;
}];

Perfect for application on the existing builder objects in Foundation in my opinion.