Click here to Skip to main content
14,037,996 members
Click here to Skip to main content
Add your own
alternative version

Stats

9.5K views
8 bookmarked
Posted 29 Feb 2016
Licenced CPOL

Learning Builder Pattern using C#

, 29 Feb 2016
Rate this:
Please Sign up or sign in to vote.
Explaining Builder Pattern in C# using a Simple TelevisionBuilder.

Introduction

Design patterns are very useful and helps in resolving many real time issues, In this article we will try to understand Builder Pattern with the help of a Sample C# Program.

Background

Builder Pattern belongs to Creational Pattern as it deals with object creation, this pattern is used multiple times in .NET Framework. One example would be ConnectionStringBuilder. Builder Pattern comes into picture when we need to create a product using a series of complex process where each process can be separated , that means we can separate each step of object creation and the same object mechanism can be used for creating similiar products or objects.

GoF describes Builder Pattern as Separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder Pattern consists of below items.

Director: Director is responsible for creation of object using Builder interface or base class.

Builder: Base class or Interface which has different steps mentioned for creating a Product.

ConcreteBuilder: Defines the concrete builder which is an implementation of above Builder. Concrete Builder will help us to create and get the below Product using series of steps mentioned in Builder.

Product: The final Product, which will be created through many complex steps.

Builder Pattern Sample using C#

Using the code

To start with th sample program, I have created a Television (Product) class as below, this Product will be constructed by the  Builder. Added different properties to show the different parts of product.

/// <summary>
/// Television - Product
/// </summary>
class Television
{
    public string Code { get; set; }
    public string DisplayTechnology { get; set; }
    public string HDFormat { get; set; }
    public string ScreenType { get; set; }
    public string Size { get; set; }
    public string Feature { get; set; }
}

Now we will create the TelevisionBuilder (Builder), which will define the complex steps for creating the Product. We can create the Builder as an Interface or Base Class. If you look at the below class definition, you can see the steps for creating the Product and Property or Method to access the created Product.

/// <summary>
/// TelevisionBuilder - Builder
/// </summary>
abstract class TelevisionBuilder
{
    protected Television television;

    public abstract void SetCode();//ProductCode
    public abstract void SetDisplayTechnology(); //LCD, LED, OLED, Plasma, CRT
    public abstract void SetHDFormat(); // Full HD, HD Ready, Ultra HD, None
    public abstract void SetScreenType(); //Curved, Flat, Standard
    public abstract void SetSize(); // 22, 32, 40, 42, 54
    public abstract void SetFeature(); //3D, Smart, Standard , HDMI Ports, USB Ports, Built in WIFI, Ethernet, Remote

    //GetProduct
    public Television Television
    {
        get { return television; }
    }

}

Defining FullHD40TVBuilder (ConcreteBuilder1) with respective implementation.

/// <summary>
/// FullHD40TVBuilder - ConcreteBuilder1
/// </summary>
class FullHD40TVBuilder : TelevisionBuilder
{

    public FullHD40TVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "FullHD40TV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LCD";
    }

    public override void SetHDFormat()
    {
        television.HDFormat = "FullHD";
    }

    public override void SetScreenType()
    {
        television.ScreenType="Flat";
    }

    public override void SetSize()
    {
        television.Size="40";
    }

    public override void SetFeature()
    {
        television.Feature = "1 HDMI Ports, 1 USB Ports, Remote";
    }
}

Defining SMARTLED54TVBuilder (ConcreteBuilder2) with respective implementation.

/// <summary>
/// SMARTLED54TVBuilder - ConcreteBuilder2
/// </summary>
class SMARTLED54TVBuilder : TelevisionBuilder
{
    public SMARTLED54TVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "SMARTLED54TV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LED";
    }

    public override void SetHDFormat()
    {
        television.HDFormat =   "FullHD";
    }

    public override void SetScreenType()
    {
        television.ScreenType="Flat";
    }

    public override void SetSize()
    {
        television.Size="54";
    }

    public override void SetFeature()
    {
        television.Feature="2 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Remote";
    }
}

Defining Curved4K65LEDTVBuilder (ConcreteBuilder3) with respective implementation.

/// <summary>
/// Curved4K65LEDTVBuilder - ConcreteBuilder3
/// </summary>
class Curved4K65LEDTVBuilder : TelevisionBuilder
{
    public Curved4K65LEDTVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "Curved4K65LEDTV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LED";
    }

    public override void SetHDFormat()
    {
        television.HDFormat =   "4K Ultra HD";
    }

    public override void SetScreenType()
    {
        television.ScreenType="Curved";
    }

    public override void SetSize()
    {
        television.Size="65";
    }

    public override void SetFeature()
    {
        television.Feature="3 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Smart Remote";
    }
}

Defining LCD22TVBuilder (ConcreteBuilder4) with respective implementation.

/// <summary>
/// LCD22TVBuilder - ConcreteBuilder4
/// </summary>
class LCD22TVBuilder : TelevisionBuilder
{
    public LCD22TVBuilder()
    {
        television = new Television();
    }

    public override void SetCode()
    {
        television.Code = "LCD22TV";
    }

    public override void SetDisplayTechnology()
    {
        television.DisplayTechnology = "LCD";
    }

    public override void SetHDFormat()
    {
        television.HDFormat = "None";
    }

    public override void SetScreenType()
    {
        television.ScreenType = "Flat";
    }

    public override void SetSize()
    {
        television.Size = "22";
    }

    public override void SetFeature()
    {
        television.Feature = "Remote";
    }
}

As of now we have defined Product, Builder and ConcreteBuilder, Now lets create TelevisionManufacturer as the Director, here the argument is Builder, and the Director takes care of calling the steps based on the requirement. 

/// <summary>
/// TelevisionManufacturer - Director
/// </summary>
class TelevisionManufacturer
{
    //Constructing Product
    public void Construct(TelevisionBuilder televisionBuilder)
    {
        //Series of Complex Process
        televisionBuilder.SetCode();
        televisionBuilder.SetDisplayTechnology();
        televisionBuilder.SetHDFormat();
        televisionBuilder.SetScreenType();
        televisionBuilder.SetSize();
        televisionBuilder.SetFeature();
    }
}

Have created a console Program to test the Builder Pattern Sample, here the end clinet is not at all worried about the complex object creation.

/// <summary>
/// Program class which demonstrates the builder usage
/// </summary>
class Program
{
    /// <summary>
    /// Main method of Program.cs
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        TelevisionBuilder builder;

        TelevisionManufacturer director = new TelevisionManufacturer();

        builder = new FullHD40TVBuilder();
        director.Construct(builder);
        Television product1 = builder.Television;

        Console.WriteLine("Code:{0}", product1.Code);

        builder = new SMARTLED54TVBuilder();
        director.Construct(builder);
        Television product2 = builder.Television;

        Console.WriteLine("Code:{0}", product2.Code);

        builder = new Curved4K65LEDTVBuilder();
        director.Construct(builder);
        Television product3 = builder.Television;

        Console.WriteLine("Code:{0}", product3.Code);

        builder = new LCD22TVBuilder();
        director.Construct(builder);
        Television product4 = builder.Television;

        Console.WriteLine("Code:{0}", product4.Code);
        //Wait for UserInteraction
        Console.ReadKey();

    }
}

Output:

Some codes are removed from above Console.Writeline to look the code simple. You can refer the Program.cs file in the attached project to see the final version.

Buider Pattern Sample Output

To explore this sample yourself you can download the attached code or create a console project named "BuilderPatternSample" and replace the content of Program.cs with below code block.

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuilderPatternSample
{
    /// <summary>
    /// Program class which demonstrates the builder usage
    /// </summary>
    class Program
    {
        /// <summary>
        /// Main method of Program.cs
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            TelevisionBuilder builder;

            TelevisionManufacturer director = new TelevisionManufacturer();

            builder = new FullHD40TVBuilder();
            director.Construct(builder);
            Television product1 = builder.Television;

            Console.WriteLine("     ┌───────────────────────────────────Code:{0}───────────────────────────────┐", product1.Code);
            Console.WriteLine("     │                         DisplayTechnology:{0}                                   │", product1.DisplayTechnology);
            Console.WriteLine("     │                         HDFormat:{0}                                         │", product1.HDFormat);
            Console.WriteLine("     │                         ScreenType:{0}                                         │", product1.ScreenType);
            Console.WriteLine("     │                         Size:{0}                                                 │", product1.Size);
            Console.WriteLine("     │                         Feature:{0}               │", product1.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            builder = new SMARTLED54TVBuilder();
            director.Construct(builder);
            Television product2 = builder.Television;

            Console.WriteLine("     ┌──────────────────────────────────Code:{0}──────────────────────────────┐", product2.Code);
            Console.WriteLine("     │        DisplayTechnology:{0}                                                    │", product2.DisplayTechnology);
            Console.WriteLine("     │        HDFormat:{0}                                                          │", product2.HDFormat);
            Console.WriteLine("     │        ScreenType:{0}                                                          │", product2.ScreenType);
            Console.WriteLine("     │        Size:{0}                                                                  │", product2.Size);
            Console.WriteLine("     │        Feature:{0}       │", product2.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            builder = new Curved4K65LEDTVBuilder();
            director.Construct(builder);
            Television product3 = builder.Television;

            Console.WriteLine("     ┌─────────────────────────────────Code:{0}────────────────────────────┐", product3.Code);
            Console.WriteLine("     │       DisplayTechnology:{0}                                                     │", product3.DisplayTechnology);
            Console.WriteLine("     │       HDFormat:{0}                                                      │", product3.HDFormat);
            Console.WriteLine("     │       ScreenType:{0}                                                         │", product3.ScreenType);
            Console.WriteLine("     │       Size:{0}                                                                   │", product3.Size);
            Console.WriteLine("     │       Feature:{0}  │", product3.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            builder = new LCD22TVBuilder();
            director.Construct(builder);
            Television product4 = builder.Television;

            Console.WriteLine("     ┌────────────────────────────────────Code:{0}─────────────────────────────────┐", product4.Code);
            Console.WriteLine("     │                         DisplayTechnology:{0}                                   │", product4.DisplayTechnology);
            Console.WriteLine("     │                         HDFormat:{0}                                           │", product4.HDFormat);
            Console.WriteLine("     │                         ScreenType:{0}                                         │", product4.ScreenType);
            Console.WriteLine("     │                         Size:{0}                                                 │", product4.Size);
            Console.WriteLine("     │                         Feature:{0}                                          │", product4.Feature);
            Console.WriteLine("     └─────────────────────────────────────────────────────────────────────────────────┘");

            //Wait for UserInteraction
            Console.ReadKey();

        }
    }


    /// <summary>
    /// Television - Product
    /// </summary>
    class Television
    {
        public string Code { get; set; }
        public string DisplayTechnology { get; set; }
        public string HDFormat { get; set; }
        public string ScreenType { get; set; }
        public string Size { get; set; }
        public string Feature { get; set; }
    }

    /// <summary>
    /// TelevisionBuilder - Builder
    /// </summary>
    abstract class TelevisionBuilder
    {
        protected Television television;

        public abstract void SetCode();//ProductCode
        public abstract void SetDisplayTechnology(); //LCD, LED, OLED, Plasma, CRT
        public abstract void SetHDFormat(); // Full HD, HD Ready, Ultra HD, None
        public abstract void SetScreenType(); //Curved, Flat, Standard
        public abstract void SetSize(); // 22, 32, 40, 42, 54
        public abstract void SetFeature(); //3D, Smart, Standard , HDMI Ports, USB Ports, Built in WIFI, Ethernet, Remote

        //GetProduct
        public Television Television
        {
            get { return television; }
        }

    }

    /// <summary>
    /// FullHD40TVBuilder - ConcreteBuilder1
    /// </summary>
    class FullHD40TVBuilder : TelevisionBuilder
    {

        public FullHD40TVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "FullHD40TV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LCD";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "FullHD";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Flat";
        }

        public override void SetSize()
        {
            television.Size = "40";
        }

        public override void SetFeature()
        {
            television.Feature = "1 HDMI Ports, 1 USB Ports, Remote";
        }
    }

    /// <summary>
    /// SMARTLED54TVBuilder - ConcreteBuilder2
    /// </summary>
    class SMARTLED54TVBuilder : TelevisionBuilder
    {
        public SMARTLED54TVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "SMARTLED54TV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LED";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "FullHD";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Flat";
        }

        public override void SetSize()
        {
            television.Size = "54";
        }

        public override void SetFeature()
        {
            television.Feature = "2 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Remote";
        }
    }

    /// <summary>
    /// Curved4K65LEDTVBuilder - ConcreteBuilder3
    /// </summary>
    class Curved4K65LEDTVBuilder : TelevisionBuilder
    {
        public Curved4K65LEDTVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "Curved4K65LEDTV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LED";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "4K Ultra HD";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Curved";
        }

        public override void SetSize()
        {
            television.Size = "65";
        }

        public override void SetFeature()
        {
            television.Feature = "3 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Smart Remote";
        }
    }

    /// <summary>
    /// LCD22TVBuilder - ConcreteBuilder4
    /// </summary>
    class LCD22TVBuilder : TelevisionBuilder
    {
        public LCD22TVBuilder()
        {
            television = new Television();
        }

        public override void SetCode()
        {
            television.Code = "LCD22TV";
        }

        public override void SetDisplayTechnology()
        {
            television.DisplayTechnology = "LCD";
        }

        public override void SetHDFormat()
        {
            television.HDFormat = "None";
        }

        public override void SetScreenType()
        {
            television.ScreenType = "Flat";
        }

        public override void SetSize()
        {
            television.Size = "22";
        }

        public override void SetFeature()
        {
            television.Feature = "Remote";
        }
    }

    /// <summary>
    /// TelevisionManufacturer - Director
    /// </summary>
    class TelevisionManufacturer
    {
        //Constructing Product
        public void Construct(TelevisionBuilder televisionBuilder)
        {
            //Series of Complex Process
            televisionBuilder.SetCode();
            televisionBuilder.SetDisplayTechnology();
            televisionBuilder.SetHDFormat();
            televisionBuilder.SetScreenType();
            televisionBuilder.SetSize();
            televisionBuilder.SetFeature();
        }
    }
}

Summary

In this article I have explained Builder Pattern with a simple C# application. I hope you have enjoyed this article and got some value addition to your knowledge. Please don't forget to mark your votes, suggestions and feedback to improve the quality of this and upcoming articles. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shemeer NS
Software Developer (Senior)
India India
Technology Specialist | CodeProject MVP | Visual Studio Gallery Contributor | Author | Geek | Netizen | Husband | ChessPlayer

Most of my articles are listed on top 5 of the respective 'Best articles of the month' and some of my articles are published on ASP.NET WebSite's Article of the Day section.

Check my contributions in Visual Studio Gallery and Code Project

Technical Blog: http://www.shemeerns.com
Facebook: http://facebook.com/shemeernsblog
Twitter : http://twitter.com/shemeerns
Google+ : http://google.com/+Shemeernsblog

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ravi Shankar K1-Mar-16 0:17
memberRavi Shankar K1-Mar-16 0:17 
Very nice article

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190425.1 | Last Updated 29 Feb 2016
Article Copyright 2016 by Shemeer NS
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid