What are some common, real world examples of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.
One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):
This builder would then spit out the HTML for me. This is much easier to read then walking through a large procedural method.
Check out Builder Pattern on Wikipedia.
You use it when you have lots of options to deal with. Think about things like jmock:
It feels a lot more natural and is...possible.
There's also xml building, string building and many other things. Imagine if
java.util.Map
had put as a builder. You could do stuff like this:I always disliked the Builder pattern as something unwieldy, obtrusive and very often abused by less experienced programmers. Its a pattern which only makes sense if you need to assemble the object from some data which requires a post-initialisation step (i.e. once all the data is collected - do something with it). Instead, in 99% of the time builders are simply used to initialise the class members.
In such cases it is far better to simply declare
withXyz(...)
type setters inside the class and make them return a reference to itself.Consider this:
Now we have a neat single class that manages its own initialization and does pretty much the same job as the builder, except that its far more elegant.