StringBuffer 和 Builder 设计模式:什么关系

StringBuider and Builder design pattern: what relation

也许我的问题会很愚蠢:我已经阅读了有关 C# 代码中的设计模式实现的信息,尤其是 Builder design pattern

我想知道 String Builder class 是否是这种设计模式的实现。

没看到:http://www.dofactory.com/net/builder-design-pattern

构建器模式适用于:

"Separate the construction of a complex object from its representation so that the same construction process can create different representations."

所以在 link 的示例中,我们有一辆汽车和一辆小型摩托车,但我们希望导演有一个共同的界面来构建两者,即使它们的构造会有所不同。

一个致命的泄露是 StringBuilder 除了 ISerializable 之外没有实现或继承自任何东西。没有什么可以让它实现通用构建器接口的方法。

尽管构建器模式共享其名称的一部分,但它们是无关的。 StringBuilder 是一种构建字符串的有效方法,不会像使用 "string1"+"string2" 那样导致许多字符串副本,因为字符串是不可变的。

引用MSDN:

A StringBuilder object maintains a buffer to accommodate expansions to the string. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.

不是真的。

考虑该模式的定义:

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

StringBuilder 总是构建一个字符串,无法创建其他任何内容。

StringBuilder 的目的是在需要许多操作来创建单个字符串时 可变 ,而不是创建大量中间字符串对象(从而加载GC).

不是真的。 StringBuilder 非常有用,因为它在连接它们之前不会创建多个不可变字符串,这可能会导致内存浪费,因为在堆上创建了新的 String 对象。相反,它使用 char[] 并在您调用 StrinBuilderObj.Append(...) 时附加它们,然后在 StringBuilderObj.ToString()

中最终请求时 returns 字符串

Builder设计模式向您展示了如何使用多个较小的对象来构建一个复杂的对象,而StrinBuilder的实现class主要是处理在连接时不创建String对象以减少内存压力在垃圾收集器上。

希望对您有所帮助!

String Builder 未实现 Builder 设计模式。

在您链接到的 Builder design pattern 中,每个具体的构建器实现都支持由基础 class 定义的接口,它们都继承自(抽象 class 构建器)。

正在查看 String Builder you can see that it only implements the interface ISerializable 的链接文档。 ISerializable 接口不包含任何支持 StringBuilder."Building" 部分的方法。

但是,您应该问自己的真正问题是为什么需要构建其他内置类型,例如通过 StringBuilder 构建字符串。 在像 C# 这样的强类型语言中,创建一堆构建器来构建其他内置类型会导致一个相当无用的接口。在实际开发中使用该接口会导致大量来回转换,并且没有实际应用程序。

设计模式需要记住的一点是,它们可以帮助开发人员快速理解问题的解决方案,但它们并非适用于所有情况。大多数时候,在处理基本的内置类型(如字符串和整数)时,框架提供的帮助绰绰有余,可以让其他开发人员理解您的解决方案。