StringBuilder 和构建器模式
我是设计模式的新手,所以我有一个关于构建器模式的问题。 今天听说Builder Pattern和Java、C#中的类StringBuilder
不同。我知道 Builder 模式的主要目标是通过几个步骤创建复杂的对象...我认为这是用它的方法 Append
创建 StringBuilder
...所以它是我很难找到区别...
你能告诉我真的有什么区别吗?如果有的话...那是什么:)?
I'm new in Design Patterns so I have one question about the Builder Pattern.
Today I heard that Builder Pattern is different from the class StringBuilder
in Java, C#. I know that main goal of the Builder Pattern is to create complex objects in few steps...I think that this is making StringBuilder
with it's method Append
...So it's hardly for me to find the difference...
Could you tell me is there really any difference and if it is...what's it :)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来您可能会混淆 StringBuilder 类和构建器设计模式。它们实际上是两种截然不同的想法。
StringBuilder 是 Java 和 .NET 允许更高效的字符串操作:(来自 MSDN)
另一方面,构建器模式是一种设计模式,它是一组类和/或接口旨在组织复杂的代码:
StringBuilder
的Append
方法只是向现有字符串添加更多字符。没有创建新的对象(构建器模式的基本功能),并且不涉及设计模式。这是对单个对象实例的单个方法调用。It sounds like you might be confusing the class StringBuilder and the Builder Design Pattern. They are actually two very different ideas.
StringBuilder is a class in Java and .NET that allows more performant string operations: (From MSDN)
The Builder Pattern on the other hand is a design pattern which is a set of classes and/or interfaces meant to organize complex code:
The
Append
method ofStringBuilder
simply adds more characters to the existing string. There are no new objects created (basic function of the builder pattern) and there is no design pattern involved. It's a single method call to a single object instance.ad 1) String 的创建没有抽象。例如,树结构是抽象的,可以用对象来表示,也可以用XML文件(实现)来表示。
ad 2) 当使用
StringBuilder
对象时,有两个协作者:Client
StringBuilder
当使用
Builder 模式时
,有四个协作者:Director
- 它向Abstract Builder
说明构建步骤是什么(如果是树结构,步骤是:创建根、添加child, ...)Abstract Builder
- 是Director
使用的抽象。Concrete Builder
- 是Abstract Builder
的具体实现(可以是 XMLBuilder、ObjectBuilder,...)Client
- 对Director< 说/code> 启动构建。
ad 1) There is no abstraction in creation of String. E.g., Tree structure is abstraction, which can be represented by objects or by XML file (implementation).
ad 2) When using
StringBuilder
object, there are two collaborators:Client
StringBuilder
When using
Builder Pattern
, there are four collaborators:Director
- it says toAbstract Builder
what are the construction steps (In case of tree structure, steps are: create root, add child, ...)Abstract Builder
- is abstraction used byDirector
.Concrete Builder
- is concrete implementation ofAbstract Builder
(Could be XMLBuilder, ObjectBuilder,...)Client
- says toDirector
to initiate the construction.分析文档,我可以说 StringBuilder 没有使用相应的模式。它使用复合模式。构建器模式不会“手动一步一步”或循环地收集对象。它有现成的解决方案。
Analyzing documentation, I can say that StringBuilder does not use corresponding pattern. It use Composite pattern. Builder pattern does not gather object "manually by your hands step-by-step" or in loop. It has ready-made solutions.