建造者设计模式
最近在研究设计模式。我正在努力寻找一个可以为该场景实现构建器模式的场景。有人有例子吗?
任何答案将不胜感激。
I have been studying design patterns lately. I am struggling with finding a scenario that I can implement builder pattern for that scenario. Has anyone got any example?
Any answer will be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
SQLOrm 是一个很好的例子,它将构建器模式与一组适当的方法名相结合,从而构建SQL 感觉就像使用 DSL。
例如
变成
SQLOrm serves as a nice example of combining the builder pattern with a proper set of methodnames making the construction of SQL feel like working with a DSL.
eg
becomes
如果您有一个非常复杂的对象(例如需要 3、4 个或更多不同的其他对象才能操作),您将使用 Builder 来正确构造该对象。
If you have a very complex object (say something that requires 3, 4 or more different other objects in order to operate), you would use a
Builder
to construct this object correctly.我喜欢在这里引用 Joshua Bloch 和他的书
Effective Java
。您肯定会遇到像这样的伸缩构造函数:
它的问题是,在某些时候,很难记住所需参数的正确顺序以及所有构造函数之间的关系。
作为替代方案(还不是构建器),您可以在此处执行经典的 POJO :
但是,它不被认为是线程安全的。
怎么解决呢?是的,构建器模式。考虑一下:
您现在将创建的 Pizza 实例将是不可变的,并且它的构建将是简单而简洁的。
查看更多 Java Builder 模式示例。
I love to refer here Joshua Bloch and his book
Effective Java
.You surely encounter
telescopic
constructors such as this one:The problem with it is that at some point, it's hard to remember the right order of the arguments you need and what the relation between all the constructors.
As an alternative (not yet a builder), you can do a classic POJO here:
But, it's not considered thread safe.
How to solve it? Yes, builder pattern. Consider this:
The instance of Pizza you will create now will be immutable and the constructing of it would be easy and concise.
Check it out for more Java Builder pattern examples.
构建器模式通常用于构造 HTML 和 XML 文档。例子:
The Builder Pattern is often used to construct HTML and XML documents. Example:
当面临许多构造函数参数时,请考虑使用构建器。以下链接详细解释也将消除所有疑虑。
http://www.drdobbs.com /jvm/creating-and-destroying-java-objects-par/208403883?pgno=2
简而言之,当构造函数参数很多而不是记住每个参数的顺序和含义时;构建器模式可用于简化参数传递,从而简化编程、提高可读性、增强参数按预期传递的信心。
Consider a builder when faced with many constructor parameters. The following link explains in good detail will clear all doubts as well.
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=2
In a nutshell when there are many constructor parameters instead of remembering the order and the meaning of each parameter; builder pattern can be used to simplify parameter passing thereby simplifying programming, improved readability, increased confidence that parameters are passed as intended.