Click here to Skip to main content
Click here to Skip to main content

Builder Design Pattern

, 16 Sep 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This article shows a case study of how we can use the Builder Pattern in Elizabeth's fun activity.

Background

In Elizabeth's day care center, the teacher helps the kids to build all kinds of toys to develop their creative skills. One of Elizabeth's favorite activities is to make animals with play-dough.

A set of molds is the tool that Elizabeth always uses to create her favorite cool animals.

One mold tool set includes five parts, including the head, body, arm, leg, and tail. Whenever Elizabeth wants to build an animal, she will use one set of each tools to make a head, body , leg, arm, and tail for that animal, and then assembles them with glue to build an animal. There are many types of animal mold tool sets that the kids can choose from.

For example: if Elizabeth wants to make a monkey, then she will pick the set of monkey molds to start.

  • Step 1. Make monkey head.
  • Step 2. Make monkey body.
  • Step 3. Make monkey leg.
  • Step 4. Make monkey arm.
  • Step 5. Make monkey tail.

Once all the five parts are finished, then Elizabeth will glue them all together and decorate it to have a monkey done as a finished product. Most likely, she will give it to me or her mom as a gift when we pick her (she will not give us the monkey if the monkey is not decorated, since it will not be looking good at all then). When she wants to make a kitten, she follows the same steps with the set of Kitten molds.

In the above scenario, an Builder Design Pattern is perfectly used by Elizabeth in her daily fun activities.

Introduction

The Builder Design Pattern helps us to slice the operations of building an object. It also enforces a process to create an object as a finished product. That means an object has to be massaged by some instructed steps before it is ready and can be used by others. The massage process could apply any restrictions or business rules for a complete building procedure (or a procedure we follow to make an object that is considered as a ready to use object). For instance, to compose an email, you can't leave the To and Subject fields blank before you can send it. In other words, an email object will be considered as an uncompleted email object (a common business rule for email) if those two fields are not filled. It has to be built (filled) before we can send it out. This article introduces an implementation of how we use the Builder Design Pattern for Elizabeth's fun activity.

Builder Design Pattern Structure

Builder.JPG

Class Diagram

Implementation Code

Builder Objects

AnimalBuilder

The AnimalBuilder class is a base abstract class. It contains all the building methods to construct a general product (Animal). A public Animal object is also declared here to implement the concept (GetResult) of returning a ready to use object. Well, it can also be a private product object; in that case, a GetResult method has to be introduced to return a ready to use product.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public abstract class AnimalBuilder
        {
            public Animal aAnimal;

            public abstract void BuildAnimalHeader();
            public abstract void BuildAnimalBody();
            public abstract void BuildAnimalLeg();
            public abstract void BuildAnimalArm();
            public abstract void BuildAnimalTail();
        }
    }
}

MonkeyBuilder

The MonkeyBuilder class is a child class of AnimalBuilder. It provides the details of each building method for a Monkey. In this class, we apply all the rules to make our product (Monkey) a ready to use object (decorated monkey). In the constructor, we also initialize the Animal object (aAnimal) to be a Monkey object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public class MonkeyBuilder : AnimalBuilder
        {

            public MonkeyBuilder()
            {
                aAnimal = new Monkey();
            }

            public override void BuildAnimalHeader()
            {
                aAnimal.Head = "Moneky's Head has been built";
            }

            public override void BuildAnimalBody()
            {
                aAnimal.Body = "Moneky's Body has been built";
            }

            public override void BuildAnimalLeg()
            {
                aAnimal.Leg = "Moneky's Leg has been built";
            }

            public override void BuildAnimalArm()
            {
                aAnimal.Arm = "Moneky's Arm has been built";
            }

            public override void BuildAnimalTail()
            {
                aAnimal.Tail = "Moneky's Tail has been built";
            }
        }
    }
}

KittenBuilder

Same as MonkeyBuilder, the KittenBuilder class will implement the details for building a Kitten object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public class KittenBuilder : AnimalBuilder
        {
            public KittenBuilder()
            {
                aAnimal = new Kitten();
            }

            public override void BuildAnimalHeader()
            {
                aAnimal.Head = "Kitten's Head has been built";
            }

            public override void BuildAnimalBody()
            {
                aAnimal.Body = "Kitten's Body has been built";
            }

            public override void BuildAnimalLeg()
            {
                aAnimal.Leg = "Kitten's Leg has been built";
            }

            public override void BuildAnimalArm()
            {
                aAnimal.Arm = "Kitten's Arm has been built";
            }

            public override void BuildAnimalTail()
            {
                aAnimal.Tail = "Kitten's Tail has been built";
            }
        }
    }
}

Product Object

Animal

The Animal class is an abstract base class that holds the basic information for a product. It helps us build multiple products.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public abstract class Animal
        {
            public string Head { get; set; }
            public string Body { get; set; }
            public string Leg { get; set; }
            public string Arm { get; set; }
            public string Tail { get; set; }

         
            //helper method for demo the Polymorphism, so we can 
            //easily tell what type object it is from client.
            public abstract void Eat();
            
            //helper method for demo the result from client
            public void ShowMe()
            {
                Console.WriteLine(Head);
                Console.WriteLine(Body);
                Console.WriteLine(Leg);
                Console.WriteLine(Arm);
                Console.WriteLine(Tail);
                Eat();

            }
        }
    }
}

Monkey Class

The Monkey class is a concrete product class that will be built from a MonkeyBuilder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public class Monkey : Animal
        {
            //helper method to show monkey's property for demo purpose
            public override void Eat()
            {
                Console.WriteLine("Since I am Monkey, I like to eat banana");
            }
        }
    }
}

Kitten Class

Same as the Monkey class, a concrete product class that will be built from a Kittenbuilder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public class Kitten : Animal
        {
            public override void Eat()
            {
                Console.WriteLine("Since I am Kitten, I like to eat kitten food");
            }
        }
    }
}

Constructor Object

Kid class

The Kid class is our constructor. It actually drives the procedure with the necessary build parts and sequence of building an animal. A concrete instance of AnimalBuilder will be passed as a different type of builder is required in order to receive different types of ready for use objects.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.askbargains.com
{
    namespace BuilderDesignPattern
    {
        public class Kid
        {
            public string Name { get; set; }

            //construct process to build an animal object, 
            //after this process completed, a object 
            //will be consider as a ready to use object.
            public void MakeAnimal(AnimalBuilder aAnimalBuilder)
            {
                aAnimalBuilder.BuildAnimalHeader();
                aAnimalBuilder.BuildAnimalBody();
                aAnimalBuilder.BuildAnimalLeg();
                aAnimalBuilder.BuildAnimalArm();
                aAnimalBuilder.BuildAnimalTail();
            }


        }
    }
}

Client App

From the client side, I create a Kid (constructor object) named Elizabeth. Elizabeth will use the monkey mold tool set to make a monkey, and she also uses the kitten mold toolkit to make a kitten. From the client, you will see I can directly use builderA.aAnimal as a ready to use object after it's been built (because it has the public property in the base AnimalBuilder class). It might be a private field which has a public method to access it as well.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using www.askbargains.com.BuilderDesignPattern;

namespace www.askbargains.com
{
    namespace Client
    {
        class Program
        {
            static void Main(string[] args)
            {
                //create a constructor object to start building
                Kid aKid = new Kid();
                aKid.Name = "Elizabeth";

                //Elizabeth use Monkey mold to make a monkey
                Console.WriteLine("{0} start making a monkey",aKid.Name);
                AnimalBuilder builderA = new MonkeyBuilder();
                aKid.MakeAnimal(builderA);
                builderA.aAnimal.ShowMe();

                //Elizabeth use Kitten mold to make a kitten
                 Console.WriteLine("{0} start making a kitten",aKid.Name);
                 AnimalBuilder builderB = new KittenBuilder();
                 aKid.MakeAnimal(builderB);
                 builderB.aAnimal.ShowMe();

                Console.Read();
            }
        }
    }
}

Once we start our client app, you will see a Monkey and a Kitten are both created. All the corresponding fields are completed to get ready to use objects. Cool!

BuilderOutput.JPG

Conclusion

In this article, I demonstrated how we can use the Builder Pattern to achieve an implementation to construct objects as ready to use based on some requirements. I have also written another article for the Visitor Design Pattern for Elizabeth's day care center: Visitor_Design_Pattern.aspx.

License

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

Share

About the Author

Allen _ Wang
Architect
United States United States
Sr Software Architect.Microsoft Certified Solutions Developer (MCSD).

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberashu_vikky13-Oct-11 21:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 17 Sep 2009
Article Copyright 2009 by Allen _ Wang
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid