Guide And Examples: Simplifying Code Using The Builder Pattern In Objective-C

In the builder pattern one creates a new objects using a dedicated builder object allowing you to avoid having to make multiple constructors, and greatly increasing the readability of your code when initializing complex objects.

This example from Klass Pieter Annema illustrates the builder pattern well with some code such as this:

Pizza *pizza = [[[[[PizzaBuilder alloc] init] setPepperoni:YES] setMushrooms:YES] setSize:12] build];

Becomes this:

PizzaBuilder *builder = [[PizzaBuilder alloc] init];
builder.size = 12;
builder.pepperoni = YES;
builder.mushrooms = YES;
Pizza *pizza = [builder build];

And using a configuration block can become even simpler:

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

You can read more about implementing the builder pattern in Objective-C over on Klaas Pieter Annema’s site, and on Joris Kluivers’ site.

You can find Joris’ Kluivers NSDate and NSURL example builder categories on Github here.

A nice set of guides and examples on implementing the builder pattern in Objective-C.

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Guide And Examples: Simplifying Code Using The Builder Pattern In Objective-C

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *