Tuesday, August 25, 2009

Builder versus Factory pattern

Copied from some other website, unknown which one...

Difference Between Builder pattern and Factory pattern
The factory pattern defers the choice of what concrete type of object to make until run time. E.g. going to a restaurant to order the special of the day. The waiter is the interface to the factory that takes the abstractor generic message "Get me the special of the day!" and returns the concrete product (i.e. Hawaiian or Spicy pizza)
The builder pattern encapsulates the logic of how to put together a complex object so that the client just requests a configuration and the builder directs the logic of building it. E.g The main contractor (builder) in building a house knows, given a floor plan, how to execute the sequence of operations (i.e. by delegating to subcontractors) needed to build the complex object. If that logic was not encapsulated in a builder, then the buyers would have to organize the subcontracting themselves ("Dear, shouldn't we have asked for the foundation to be laid before the roofers showed up?")
The factory is concerned with what is made, the builder with how it is made. Design patterns points out that Abstract factory is similar to builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract factory's emphasis is on families of product objects (either simple or complex). Builder returns the product as the final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

No comments:

Post a Comment