什么时候使用Builder Pattern? [英] When would you use the Builder Pattern?
问题描述
使用Builder Pattern的一些常用,真实世界示例是什么?它买什么?为什么不使用工厂模式?
What are some common, real world examples of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?
推荐答案
构建器和工厂IMHO之间的关键区别是,构建器对于你需要做许多事情才能建立一个对象。例如,想像一个DOM。您必须创建大量的节点和属性来获取最终对象。工厂可以在一个方法调用中轻松创建整个对象。
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.
使用构建器的一个例子是构建一个XML文档,我已经使用这个模型在构建HTML片段时,例如我可能有一个Builder用于构建一个特定类型的表,它可能有以下方法(参数未显示):
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):
BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()
然后,这个构建器会为我吐出HTML。这很容易阅读,然后走大程序方法。
This builder would then spit out the HTML for me. This is much easier to read then walking through a large procedural method.
查看维基百科上的生成器模式。
这篇关于什么时候使用Builder Pattern?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!