Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a real-life use for the builder design pattern?

I've read about it, I understand it's basic function--I'd like to know an example of a common, real-life use for this pattern.

For reference, I work mostly with business applications, web and windows, using the Microsoft stack.

like image 452
alchemical Avatar asked Dec 22 '22 11:12

alchemical


2 Answers

Think of an Itinerary builder. There are lots of things you can add to you Itinerary like hotels, rental cars, airline flights and the cardinality of each is 0 to *. Alice might have a car and hotel while Bob might have two flights, no car and three hotels.

It would be very hard to create an concrete factory or even an abstract factory to spit out an Itinerary. What you need is a factory where you can have different steps, certain steps happen, others don't and generally produce very different types of objects as a result of the creation process.

In general, you should start with factory and go to builder only if you need higher grain control over the process.

Also, there is a good description, code examples and UML at Data & Object Factory.

like image 63
JP Alioto Avatar answered Dec 25 '22 00:12

JP Alioto


Key use cases:

  • When the end result is immutable, but doing it all with a constructor would be too complicated
  • When I want to partially build something and reuse that partially built thing, but customize it at the end each time
  • When you start with the factory pattern, but the thing being built by the factory has too many permutations

In summary, builder keeps your constructors simple, yet permits immutability.

You said C#, but here's a trivial Java example:

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World!");
System.out.println(sb.toString());

As opposed to:

String msg = "";
msg += "Hello";
msg += " ";
msg += "World!";
System.out.println(msg);
like image 41
Chris Dolan Avatar answered Dec 25 '22 00:12

Chris Dolan