Wednesday, May 9, 2012

Simple Builder Design Pattern


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

namespace Builder
{
    class Program
    {
        static void Main(string[] args)
        {
            Pizza pizza = new Builder(12).Cheese(true).Pepperoni(true).Bacon(true).Build();
            Console.ReadLine();
        }
    }

    public class Pizza
    {
        private int size;
        private bool cheese;
        private bool pepperoni;
        private bool bacon;

        public Pizza(Builder builder)
        {
            size = builder.size;
            cheese = builder.cheese;
            pepperoni = builder.pepperoni;
            bacon = builder.bacon;
        }

    }

    public class Builder
    {
        //required
        public int size;

        //optional
        public bool cheese = false;
        public bool pepperoni = false;
        public bool bacon = false;

        public Builder(int size)
        {
            this.size = size;
        }

        public Builder Cheese(bool value)
        {
            this.cheese = value;
            return this;
        }

        public Builder Pepperoni(bool value)
        {
            this.pepperoni = value;
            return this;
        }

        public Builder Bacon(bool value)
        {
            this.bacon = value;
            return this;
        }

        public Pizza Build()
        {
            return new Pizza(this);
        }
    }

}


//Example 2


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

namespace Builder
{
    class Program
    {
        static void Main(string[] args)
        {
            portfolio p = new builder().withA(false).withB(true).withC(true).build();
            Console.ReadLine();
        }
    }

    public class portfolio
    {
        public bool a = false;
        public bool b = false;
        public bool c = false;
    }

    public class builder
    {

        portfolio p = new portfolio();

        public builder withA(bool v)
        {
            p.a = v;
            return this;
        }

        public builder withB(bool v)
        {
            p.b = v;
            return this;
        }

        public builder withC(bool v)
        {
            p.c = v;
            return this;
        }

        public portfolio build()
        {
            return p;
        }


    }
}

No comments:

Post a Comment