Get Updates By E-mail 

Article Written By:
Johann Dowa

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.


  •  
  •  
  •  
  •  
  •  

Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.

Comments