Ricket
Ricket

Reputation: 34067

Is there a specific term for the Builder pattern where each method returns `this`?

I know this is the Builder pattern, but it's a modified form of it. Whereas the Wikipedia article on Builder pattern gives the example:

pizzaBuilder.createNewPizzaProduct();
pizzaBuilder.buildDough();
pizzaBuilder.buildSauce();
pizzaBuilder.buildTopping();
Pizza p = pizzaBuilder.getPizza();

Is there a specific name for the modified Builder pattern which looks like:

Pizza p = pizzaBuilder.createNewPizzaProduct().buildDough().buildSauce().buildTopping();

This is best seen in the jQuery library, where you can do something like:

$('li.item-a').parent().css('background-color', 'red');

Where each method, including the initial $(), returns a jQuery object which typically represents a set of page elements, and each method operates on that set in some way.

Upvotes: 8

Views: 1259

Answers (4)

ChrisF
ChrisF

Reputation: 137148

It can be called a Fluent interface:

In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is a way of implementing an object oriented API in a way that aims to provide for more readable code.

A fluent interface is normally implemented by using method chaining to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining)

Upvotes: 3

mookid8000
mookid8000

Reputation: 18628

I would call the technique "method chaining".

(pretty much in accordance with wikipedia...)

And yes, method chaining can be used to build fluent interfaces.

Upvotes: 3

Mark Seemann
Mark Seemann

Reputation: 233162

I've seen this called a Fluent Builder several places.

This makes a lot of sense, since it's basically a combination of a Fluent Interface and the Builder design pattern.

Upvotes: 9

kennytm
kennytm

Reputation: 523374

In C++, it is called (at least by one site) "Named Parameter Idiom".

Upvotes: 3

Related Questions