C# Corner

The Builder Pattern in .NET

How to separate complex object construction from its representation using the Builder design pattern in C#.

The Builder Pattern is a common software design pattern that's used to encapsulate the construction logic for an object. This pattern is often used when the construction process of an object is complex. It's also well suited for constructing multiple representations of the same class. First, I'll go over the basics of the pattern, and then I'll provide an example to crystallize the concepts.

Core Concepts
The Builder Pattern is comprised of four components: a builder interface, a concrete builder, a director and a product. The builder interface defines a template for the steps to construct the product. The concrete builder implements the builder interface and provides an interface for getting the product. The director actually constructs the object through the builder interface. The product is the end object that's constructed.

Now that you understand the concepts of the pattern, I'll go over a full implementation of the pattern. My simple example encapsulates the process of brewing a beer. The first step is to define the Beer class, which is the product that will be built. The Beer class is a simplified representation of a beer that includes a label, volume, price and potency. I also added a ToString method override to concisely display the full contents of the object. See Listing 1 for the Beer class source code.

Next, I define the IBeerBuilder interface that specifies the necessary steps of constructing a beer object. I've also added a GetBeer method that returns the beer object at any time of the construction process. See Listing 2 for the full IBeerBuilder interface source code.

Now that I've defined the builder interface and the product, a concrete builder class that implements the IBeerBuilder interface is needed. In this case, I've created two beer builders, one for an amber ale (Listing 3) and one for a stout (Listing 4).

Fully Constructed Object
The final piece is to define a director class that will take a given IBeerBuilder interface and use it to execute the necessary steps to brew the beer. The BrewMaster class includes three methods: SetBeerBuilder, GetBeer and BrewBeer. The SetBeerBuilder class allows the consumer to set the IBeerBuilder interface to build the needed beer. The BrewBeer method executes the steps in order to fully brew the beer using the set IBeerBuilder, and the GetBeer method returns the fully constructed Beer object. See Listing 5 for the full BrewMaster director class source code.

Finally, to fully test the Builder Pattern implementation: First, create a new BrewMaster instance; then call the SetBeerBuilder method with a concrete IBeerBuilder object instance. Next, call the BrewBeer method on the BrewMaster instance. Lastly, call the GetBeer method on the BrewMaster to get the fully constructed Beer instance. The same BrewMaster instance can be used to create multiple Beer object representations as represented in Listing 6 and Figure 1.


[Click on image for larger view.]
Figure 1. Finished Builder Pattern Demo App

As you can see, the true strength of the Builder Pattern is that it lets you break up the construction of a complex object. Not only that, it also allows you to hide the construction process from the consumer, thus allowing for additional representations of the product to be added with ease. The pattern also encourages separation of concerns and promotes application extensibility.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events