17

I would like to see how is Builder pattern used in real world applications/APIs. The examples I found are all pizzas, cakes, cars et cetera (plus the parser example from the GoF book).

Could you please tell me about some usages of this patten in real-world applications/APIs, preferably from the world of C++, .NET or PHP (as those are the languages I'm familiar with).

Thanks.

Matěj Zábský
  • 16,909
  • 15
  • 69
  • 114

3 Answers3

9

Update: I recently came across an even better example (imo). Checkout the JobBuilder and TriggerBuilder implementations in the Quartz scheduler package: http://quartz-scheduler.org/api/2.1.5/

Also, when I have time, just for fun/practice, I try to write examples of all GoF patterns in java. Just recently, I used the Builder pattern to make it easy to generate different types of Sitemaps (google site map vs, html site map, etc). The code is in java, but you might be useful: https://github.com/dparoulek/java-koans/tree/master/src/main/java/com/upgradingdave/koans/builder

Good question, I'd be interested in seeing more modern examples too.

Upgradingdave
  • 12,916
  • 10
  • 62
  • 72
  • @Dave Paroulek - Check this [post](http://stackoverflow.com/questions/15461083/builder-pattern-which-variant-is-preferred) and explanation on why it is not good. Sharing something I too learnt today - The immutability aspect of Builder pattern! – Zeena Feb 04 '15 at 10:15
4

Builder pattern is used in javax.json.Json and javax.json.JsonBuilder classes while building Json objects.

Good explanation is at http://www.programcreek.com/java-api-examples/index.php?api=javax.json.JsonObjectBuilder and also check out its official documentation.

JsonObjectBuilder b = Json.createObjectBuilder().
            add( "report", Json.createObjectBuilder().
                 add( "reportId", reportId ).
                 add( "title", title ).
                 add( "subtitle", subTitle == null ? "" : subTitle ).
                 add( "created", created.toString() ).
                 add( "description", description == null ? "" : description ).
                 add( "data", report )
            );
return b.build();
Anoop
  • 5,540
  • 7
  • 35
  • 52
3

Actually a very good real-life example is Active Record QueryBuilder example.

You can dig into the Laravel Eloquent module and check those Query builder classes...

A quick example of how it could look:

interface SqlQueryBuilder
{
    public function select(string $table, array $fields): SqlQueryBuilder;

    public function where(string $field, string $value, string $operator = '='): SqlQueryBuilder;

    public function limit(int $start, int $offset): SqlQueryBuilder;

    // ... other methods

    public function getSQL(): string;
}

class MysqlQueryBuilder implements SqlQueryBuilder
{
    // ...
}

class PostgresQueryBuilder extends MysqlQueryBuilder
{
    // ...
}
user991
  • 1,339
  • 2
  • 24
  • 45