你什么时候会使用建造者模式? [英] When would you use the 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?
推荐答案
恕我直言,构建器和工厂之间的主要区别在于构建器在您需要做很多事情来构建对象时很有用.例如,想象一个 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 片段时使用了这个模型,例如我可能有一个构建器来构建特定类型的表格,它可能有以下方法 (参数未显示):
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 than walking through a large procedural method.
查看维基百科上的构建器模式.
这篇关于你什么时候会使用建造者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!