Real-world examples of the Builder pattern

后端 未结 3 1879
孤独总比滥情好
孤独总比滥情好 2021-02-04 06:21

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

3条回答
  •  梦如初夏
    2021-02-04 06:29

    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
    {
        // ...
    }
    

提交回复
热议问题