What is the difference between the Builder design pattern and the Factory design pattern?
Which one is more advantageous and why ?
How do I represent my findings as a graph if I want to test and compare/contrast these patterns ?
What is the difference between the Builder design pattern and the Factory design pattern?
Which one is more advantageous and why ?
How do I represent my findings as a graph if I want to test and compare/contrast these patterns ?
With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.
From Wikipedia:
- Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
- Builder often builds a Composite.
- Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
- Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
Wikipedia entry for factory design pattern: http://en.wikipedia.org/wiki/Factory_method_pattern
Wikipedia entry for builder design pattern: http://en.wikipedia.org/wiki/Builder_pattern
The Factory pattern can almost be seen as a simplified version of the Builder pattern.
In the Factory pattern, the factory is in charge of creating various subtypes of an object depending on the needs.
The user of a factory method doesn't need to know the exact subtype of that object. An example of a factory method createCar might return a Ford or a Honda typed object.
In the Builder pattern, different subtypes are also created by a builder method, but the composition of the objects might differ within the same subclass.
To continue the car example you might have a createCar builder method which creates a Honda-typed object with a 4 cylinder engine, or a Honda-typed object with 6 cylinders. The builder pattern allows for this finer granularity.
Diagrams of both the Builder pattern and the Factory method pattern are available on Wikipedia.
The builder design pattern describes an object that knows how to craft another object of a specific type over several steps. It holds the needed state for the target item at each intermediate step. Think what StringBuilder goes through to produce a final string.
The factory design pattern describes an object that knows how to create several different but related kinds of object in one step, where the specific type is chosen based on given parameters. Think of the serialization system, where you create your serializer and it constructs the desired in object all in one load call.
Builder Pattern and Factory pattern, both seem pretty similar to naked eyes because they both create objects for you.
This real-life example will make the difference between the two more clear.
Suppose, you went to a fast food restaurant and you ordered Food.
Pizza
Capsicum, Tomato, BBQ chicken, NO PINEAPPLE
So different kinds of foods are made by Factory pattern but the different variants(flavors) of a particular food are made by Builder pattern.
Different kinds of foods
Pizza, Burger, Pasta
Variants of Pizza
Only Cheese, Cheese+Tomato+Capsicum, Cheese+Tomato etc.
You can see the sample code implementation of both patterns here
Builder Pattern
Factory Pattern
| Builder | Factory |
|---|---|
| Return only single instance to handle complex object construction | Return various instances on multiple constructors |
| No interface required | Interface driven |
| Inner classes is involved (to avoid telescopic constructors) | Subclasses are involved |
Telescoping Constructor Pattern
Analogy:
Both are Creational patterns, to create Object.
1) Factory Pattern - Assume, you have one super class and N number of sub classes. The object is created depends on which parameter/value is passed.
2) Builder pattern - to create complex object.
Ex: Make a Loan Object. Loan could be house loan, car loan ,
education loan ..etc. Each loan will have different interest rate, amount ,
duration ...etc. Finally a complex object created through step by step process.
Factory: Used for creating an instance of an object where the dependencies of the object are entirely held by the factory. For the abstract factory pattern, there are often many concrete implementations of the same abstract factory. The right implementation of the factory is injected via dependency injection.
Builder: Used to build immutable objects, when the dependencies of the object to be instantiated are partly known in advance and partly provided by the client of the builder.
The main advantage of the builder pattern over factory pattern is in case if you want to create some standard object with lots of possible customizations, but you usually end up customizing just a few.
For example, if you want to write an HTTP Client - you'll set up some default parameters like default write/read timeout, protocols, cache, DNS, interceptors, etc.
Most of the users of your client will just use those default parameters, while some other users might want to customize some of the other parameters. In some cases, you'll just want to change timeouts and use the rest as it is, while in other cases you might need to customize for example the cache.
Here are possible ways of instantiating your client (taken from OkHttpClient):
//just give me the default stuff
HttpClient.Builder().build()
//I want to use custom cache
HttpClient.Builder().cache(MyCache()).build()
//I want custom connection timeout
HttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).build()
//I am more interested in read/write timeout
HttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS).build()
If you'd use a factory pattern for this, you'll end up writing a lot of methods with all possible combinations of creational parameters. With the builder, you just specify those you care about and let the builder build it for you taking care of all those other params.
The main difference between them is that the Builder pattern primarily describes the creation of complex objects step by step. In the Abstract Factory pattern, the emphasis is on families of objects-products. Builder returns the product in the last step. While in the Abstract Factory pattern the product is available immediately.
Example: Let say that we are creating Maze
1. Abstract Factory:
Maze* MazeGame::CreateMaze (MazeFactory& factory) {
Maze* maze = factory.MakeMaze(); /// product is available at start!!
/* Call some methods on maze */
return maze;
}
2. Builder:
Maze* MazeGame::CreateMaze (MazeBuilder& builder) {
builder.buildMaze(); /// We don't have access to maze
/* Call some methods on builder */
return builder.GetMaze();
}
IMHO
Builder is some kind of more complex Factory.
But in Builder you can instantiate objects with using another factories, that are required to build final and valid object.
So, talking about "Creational Patterns" evolution by complexity you can think about it in this way:
Dependency Injection Container -> Service Locator -> Builder -> Factory
Many designs start by using Factory Method (less complicated and more customizable via subclasses) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, but more complicated).
Builder focuses on constructing complex objects step by step.
Implementing it:
Abstract Factory specializes in creating families of related objects. Abstract Factory returns the product immediately, whereas Builder lets you run some additional construction steps before fetching the product.
You can use Abstract Factory along with Bridge. This pairing is useful when some abstractions defined by Bridge can only work with specific implementations. In this case, Abstract Factory can encapsulate these relations and hide the complexity from the client code.