Builder,Pattern

Erhan 8/7/2016 0

Builder Pattern

C#
 Challenge
In a computer manufacturing unit, depending on the configuration they have to
create computers. The challenge is that the computer peripheral is chosen in the
runtime. The order can contain n number of computers based on the same
configuration. This could be the right example to implement the Builder pattern
where each robot will be setup with a particular computer configuration. The robot
will continue creating the same configuration based computer n times.
Computer Peripherals
Processor: Intel / AMD
Monitor: Samsung / LG
Speakers: None / Stereo / Surround
How to provide a better solution that allows to choose the peripherals at runtime?
Definition
GoF Definition: "Separate the construction of a complex object from its
representation so that the same construction processes can create different
representations"
Implementation
We can use the Builder Pattern to address the above problem. The pattern allows
predefined processes with the steps configurable in the runtime.
The application contains a Windows Form which allows the user to choose the
configuration. The virtual factory provides up to 3 robots to be added before the
actual assembling takes place.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BuilderPattern.Classes
{
    public class Factory
    {
        public void Execute(Control. ControlCollection controlCollection)
        {
            foreach (Robot robot in controlCollection)
            {
                ThreadStart threadStart = new ThreadStart(robot.Create);
                Thread thread = new Thread(threadStart);
                thread.Start();
            }
        }
    }
}


*************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using BuilderPattern.Resources;

namespace BuilderPattern.Classes
{
    /// <summary>
    /// Robot class implementing builder pattern
    /// </summary>
    public partial class Robot : UserControl
    {
        /// <summary>
        /// Dictionary containing peripheral and the option
        /// </summary>
        public Dictionary <Peripheral, string> Peripherals = new Dictionary<Peripheral , string>();

        /// <summary>
        /// The core method used to create different representations
        /// </summary>
        public void Create()
        {
            while (true )
            {
                // Create new Computer
                _computer = new Bitmap (Images.Computer);

                foreach (Peripheral peripheral in Peripherals.Keys)
                {
                    if (peripheral == Peripheral .Processor)
                        AssembleCPU(Peripherals[peripheral]);

                    if (peripheral == Peripheral .Monitor)
                        AssembleMonitor(Peripherals[peripheral]);

                    if (peripheral == Peripheral .Speakers)
                        AssembleSpeakers(Peripherals[peripheral]);

                }

                AddToStore();
            }
        }

        public Robot()
        {
            InitializeComponent();
        }

        private Bitmap _computer;

        private PictureBox _pictureBox;

        private void AddToStore()
        {
            _pictureBox = new PictureBox ();
            _pictureBox.BorderStyle = BorderStyle.FixedSingle;
            _pictureBox.Image = _computer;
            _pictureBox.Height = _computer.Height;
            _pictureBox.Width = _computer.Width;

            try
            {
                MyDelegate del = new MyDelegate(AddToParent);
                IAsyncResult result = Store.BeginInvoke(del);
                while (!result.IsCompleted)
                    Application.DoEvents();
            }
            catch
            {
                // As no stop button provided we have to abort the thread
                Thread.CurrentThread.Abort();
            }
        }

        private void AddToParent()
        {
            Store.Controls.Add(_pictureBox);

            if (Store.Controls.Count > 1)
            {
                Control lastControl = Store.Controls[Store.Controls.Count - 2];
                _pictureBox.Top = lastControl.Top   lastControl.Height   1;
                Store.ScrollControlIntoView(_pictureBox);
            }
        }

        private delegate void MyDelegate();

        private const int Delay = 500;

        public void AssembleCPU(string model)
        {
            AddLog( "Assembling CPU "   model   ".." );

            Thread.Sleep(Delay);
            Application.DoEvents();
        }

        public void AssembleMonitor(string model)
        {
            AddLog( "Assembling Monitor "   model   ".." );

            Thread.Sleep(Delay);
            Application.DoEvents();
        }

        public void AssembleSpeakers(string model)
        {
            AddLog( "Assembling Speakers "   model   ".." );

            if (model == "Stereo" )
                _computer = new Bitmap (Images.ComputerWith2Speaker);
            else
                _computer = new Bitmap (Images.ComputerWithSurroundSpeakers);

            Thread.Sleep(Delay);
            Application.DoEvents();
        }

        private void AddLog(string msg)
        {
            LogBox.Items.Add(msg);

            LogBox.SelectedIndex = LogBox.Items.Count - 1;
        }
    }

    #region "Related Types#

    public enum Peripheral
    {
        Processor,
        Monitor,
        Speakers
    }

    #endregion
}

**************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BuilderPattern.Classes;
using System.Threading;

namespace BuilderPattern
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false ;
        }

        private void AddRobot_Click(object sender, EventArgs e)
        {
            if (Factory.Controls.Count < 3)
            {
                string cPU = IntelCPU.Text;
                if (AMDCPU.Checked)
                    cPU = AMDCPU.Text;

                string monitor = SamsungMonitor.Text;
                if (LGMonitor.Checked)
                    monitor = LGMonitor.Text;

                string speakers = StereoSpeakers.Text;
                if (SurroundSpeakers.Checked)
                    speakers = SurroundSpeakers.Text;

                // Create the robot
                Robot robot = new Robot();
                robot.Peripherals.Add( Peripheral.Processor, cPU);
                robot.Peripherals.Add( Peripheral.Monitor, monitor);
               
                if (!NoSpeakers.Checked)
                    robot.Peripherals.Add( Peripheral.Speakers, speakers);

                AddToFactory(robot);
            }
            else
                MessageBox.Show("Maximum 3 robots allowed!" );
        }

        private void AddToFactory(Robot robot)
        {
            int left = 10, top = 14;

            if (Factory.Controls.Count > 0)
            {
                Control lastControl = Factory.Controls[Factory.Controls.Count - 1];
                left = lastControl.Left   lastControl.Width   5;
            }

            Factory.Controls.Add(robot);

            robot.Left = left;
            robot.Top = top;
        }

        private void StartRun_Click(object sender, EventArgs e)
        {
            if (Factory.Controls.Count > 0)
            {
                StartRun.Enabled = false;
                new Factory ().Execute(Factory.Controls);
            }
            else
                MessageBox.Show("No Robots added!" );
        }
    }
}

  
 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments