StringBuilder and Builder Pattern

user551761 picture user551761 · Mar 8, 2011 · Viewed 13.4k times · Source

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 :)?

Answer

Paul Sasik picture Paul Sasik · Mar 8, 2011

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 String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

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 builder pattern is a software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance to the composite pattern, a structural pattern.

The Append method of StringBuilder 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.