Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 339
Ricket Avatar asked May 28 '10 15:05

Ricket


2 Answers

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.

like image 113
Mark Seemann Avatar answered Oct 02 '22 13:10

Mark Seemann


I would call the technique "method chaining".

(pretty much in accordance with wikipedia...)

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

like image 34
mookid8000 Avatar answered Oct 02 '22 13:10

mookid8000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!