Thursday 22 December 2016

Understanding and Implementing Builder Pattern in C#

When we have an application that need to create an object which has to be constructed using many different objects, we find our client code cluttered with the details of the various Part objects that needs to be assembled together to create the resulting object.
To illustrate on above point let us take an example of mobile phone manufacturing system. Lets assume that we have a system installed at one of the mobile phone vendors. Now the manufacturer may decide to create a phone based on parameters like Touchscreen, Operating System, Battery and Stylus. Now if we have the objects for all these parts then creation of product with any combination of above parts would lead to a very complex and unmanageable code in the client application i.e. the module that will decide what kind of phone needs to be built.
Builder pattern is meant to solve such problems. GoF defines Builder pattern as:
Separate the construction of a complex object from its representation so that the same construction process can create different representations. 
What this means is that we will have to design the system in such a way that the client application will simply specify the parameters that should be used to create the complex object and the builder will take care of building the complex object. Let us visualize the class diagram of Builder Pattern. 

Now lets see what each class in the above class diagram is meant for
  • ConcreteBuilder: Concrete classes that will create the complex Product. this will keep track of what Product it has created i.e. assembled what parts and this will be used by the client to get the Product object.
  • Builder: This is the interface for creating the actual products
  • Director: This is the Client code that will specify the parts needs to be put tegether to to create the actual concrete Product.
  • Product: This is the object that will be created by assembling many parts.

Using the code

Let us now follow the same lines as defined in the builder pattern and try to implement a basic builder pattern by solving the similar mobile phone manufacturer problem that we discussed earlier.
Let us start by having the mechanism to specify the Parts in place. Let us simple define some enums for each part so that we can create a Product by assembling the various part types
// Some helper enums to identify various parts
public enum ScreenType
{
    ScreenType_TOUCH_CAPACITIVE,
    ScreenType_TOUCH_RESISTIVE,
    ScreenType_NON_TOUCH
};

public enum Battery
{
    MAH_1000,
    MAH_1500,
    MAH_2000
};

public enum OperatingSystem
{
    ANDROID,
    WINDOWS_MOBILE,
    WINDOWS_PHONE,
    SYMBIAN
};

public enum Stylus
{
    YES,
    NO
};
Now let us look the the Product class. We need to have a Product that can be created by assembling there parts so lets have a class called MobilePhone which will be the Product class for us.
// This is the "Product" class
class MobilePhone
{
    // fields to hold the part type
    string phoneName;       
    ScreenType phoneScreen;
    Battery phoneBattery;
    OperatingSystem phoneOS;
    Stylus phoneStylus;

    public MobilePhone(string name)
    {
        phoneName = name;
    }

    // Public properties to access phone parts

    public string PhoneName
    {
        get { return phoneName; }            
    }

    public ScreenType PhoneScreen
    {
        get { return phoneScreen; }
        set { phoneScreen = value; }
    }        

    public Battery PhoneBattery
    {
        get { return phoneBattery; }
        set { phoneBattery = value; }
    }        

    public OperatingSystem PhoneOS
    {
        get { return phoneOS; }
        set { phoneOS = value; }
    }       

    public Stylus PhoneStylus
    {
        get { return phoneStylus; }
        set { phoneStylus = value; }
    }

    // Methiod to display phone details in our own representation
    public override string ToString()
    {
        return string.Format("Name: {0}\nScreen: {1}\nBattery {2}\nOS: {3}\nStylus: {4}",
            PhoneName, PhoneScreen, PhoneBattery, PhoneOS, PhoneStylus);
    }
}
Now since we have the Product class ready with us lets work on creating the Builder. The Builder should provide the functions for creating each of the parts for any phone. So let us create an interface for Builder as IPhoneBuilder and look at it.
// This is the "Builder" class
interface IPhoneBuilder
{
    void BuildScreen();
    void BuildBattery();
    void BuildOS();
    void BuildStylus();
    MobilePhone Phone { get;}
}
Now we have the Builder interface ready, the next thing would be to have the ConcreteBuilder objects in place. Let us assume that the manufacturer is planning for an Android phone and one Windows Phone so we will be needing two ConcreteBuilder for these phones i.e. AndroidPhoneBuilder and WindowsPhoneBuilder. Inside these builders we can specify the type of parts we want to use for each phone.
// This is the "ConcreteBuilder" class
class AndroidPhoneBuilder : IPhoneBuilder
{
    MobilePhone phone;

    public AndroidPhoneBuilder()
    {
        phone = new MobilePhone("Android Phone");
    }

    #region IPhoneBuilder Members

    public void BuildScreen()
    {
        phone.PhoneScreen = ScreenType.ScreenType_TOUCH_RESISTIVE;
    }

    public void BuildBattery()
    {
        phone.PhoneBattery = Battery.MAH_1500;
    }

    public void BuildOS()
    {
        phone.PhoneOS = OperatingSystem.ANDROID;
    }

    public void BuildStylus()
    {
        phone.PhoneStylus = Stylus.YES;
    }
    
    // GetResult Method which will return the actual phone
    public MobilePhone Phone
    {
        get { return phone; }
    }

    #endregion
}

// This is the "ConcreteBuilder" class
class WindowsPhoneBuilder : IPhoneBuilder
{
    MobilePhone phone;

    public WindowsPhoneBuilder()
    {
        phone = new MobilePhone("Windows Phone");
    }

    #region IPhoneBuilder Members

    public void BuildScreen()
    {
        phone.PhoneScreen = ScreenType.ScreenType_TOUCH_CAPACITIVE;
    }

    public void BuildBattery()
    {
        phone.PhoneBattery = Battery.MAH_2000;
    }

    public void BuildOS()
    {
        phone.PhoneOS = OperatingSystem.WINDOWS_PHONE;
    }

    public void BuildStylus()
    {
        phone.PhoneStylus = Stylus.NO;
    }

    // GetResult Method which will return the actual phone
    public MobilePhone Phone
    {
        get { return phone; }
    }

    #endregion
}
And finally lets have the Director class. Lets create a Director class that will have the Construct method accepting an IPhoneBuilder and then calling the respective functions of the ConcreteBuilders internally.
// This is the "Director" class
class Manufacturer
{
    public void Construct(IPhoneBuilder phoneBuilder)
    {
        phoneBuilder.BuildBattery();
        phoneBuilder.BuildOS();
        phoneBuilder.BuildScreen();
        phoneBuilder.BuildStylus();
    }
}
Now we have wrapped around the functionality of building complex Products in form of Builder Design Pattern. Now when we look at the client code we can see how clean it is to create any product.
class Program
{
    static void Main(string[] args)
    {
        // Lets create the Director first
        Manufacturer newManufacturer = new Manufacturer();
        // Lets have the Builder class ready
        IPhoneBuilder phoneBuilder = null;

        // Now let us create an android phone
        phoneBuilder = new AndroidPhoneBuilder();
        newManufacturer.Construct(phoneBuilder);
        Console.WriteLine("A new Phone built:\n\n{0}", phoneBuilder.Phone.ToString());

        // Now let us create a Windows Phone
        phoneBuilder = new WindowsPhoneBuilder();
        newManufacturer.Construct(phoneBuilder);
        Console.WriteLine("A new Phone built:\n\n{0}", phoneBuilder.Phone.ToString());
    }
}
Now if we need to create more Products only a ConcreteBuilder would be needed and rest all the codebase will remain the same. The client code can also create complex Products easily with this pattern in place. Lets look at the output of our program.

Before wrapping up let is look at the class diagram of our application and compare it with the class diagram of Builder Pattern.

Tuesday 20 December 2016

Why we do create object instance from Interface instead of Class?

Interfaces define that a class MUST be able to do something. This means that you know the object being worked on will do what you want to be able to do. It allows you greater freedom and advantages of OOP. This is a deep topic but a very basic example would be this:
public interface IAnimal
{
    string Speak();
}

public class Dog : IAnimal
{
    public string Speak()
    {
        return "Woof, woof";
    }
} 

public class Cat : IAnimal
{
    public string Speak()
    {
        return "Meow";
    }
} 

public class Parrot : IAnimal
{
    public string Speak()
    {
        return "Sqwark!";
    }
} 
Then you could use any animal you like!
class Program
{
    static void Main(string[] args)
    {
        // Writes Woof, Woof
        IAnimal animal = new Dog();
        Console.WriteLine(animal.Speak());        

        // Now writes Meow
        animal = new Cat();
        Console.WriteLine(animal.Speak());

        // Now writes Sqwark etc
        animal = new Parrot();
        Console.WriteLine(animal.Speak());
    }
}
This also allows you to then get into things like Inversion Of Control where you would take an item in like this and you could pass a dog, cat or parrot and the method would always work, not knowing or caring which animal it was:
public void ShoutLoud(IAnimal animal)
{
    MessageBox.Show("Shout " + animal.Speak());
}
This then makes ShoutLoud unit testable because you could use a mock object rather than a real animal. It basically makes your code flexible and dynamic rather than rigid and tightly coupled.
Also, expanding on Matthew's question. In C# you can only inherit from one base class but you can have multiple interfaces. So, you could have:
public class Dog : IAnimal, IMammal, ICarnivor
This allows you to have small interfaces (recommended) that then allow you to build up so giving maximum control over what an item can / must do.

Saturday 3 December 2016

Calling Server Side Method Using jQuery/Ajax

With this post I would show how to call server side method from client side. Here we will use jQuery to utilize the Ajax Capabilities which will help us to get/post data to/from server Asynchronously. There are many methods available to perform an async callback to the server. Here I will show a simple example as in how to call a code behind Webmethod.
For simplicity I would be calling the code behind method on a Button Click. Here is the code:
Aspx markup:
   1: <asp:Button ID="Button1" runat="server" Text="Click" />
   2: <br /><br />
   3: <div id="myDiv"></div>
jQuery:
   1: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
   2:   <script type ="text/javascript">
   3:       $(document).ready(function () {
   4:           $('#<%=Button1.ClientID %>').click(function () {
   5:               $.ajax({
   6:                   type: "POST",
   7:                   url: "WebForm1.aspx/ServerSideMethod",
   8:                   data: "{}",
   9:                   contentType: "application/json; charset=utf-8",
  10:                   dataType: "json",
  11:                   async: true,
  12:                   cache: false,
  13:                   success: function (msg) {
  14:                       $('#myDiv').text(msg.d); 
  15:                   }
  16:               })
  17:               return false;
  18:           });
  19:       });
  20:   </script>
Code Behind (C#):
   1: [WebMethod]
   2:    public static string ServerSideMethod()
   3:    {
   4:        return "Message from server.";
   5:    }
In the above code, the aspx markup contains a button on click of which we would call the server side method named ServerSideMethod(). The div would show the message returned from the server. When you run the code above and click the button, it would the div would show the message "Message from server".
If you want to send parameters to your code behind method, you would change the line 8 in the above jQuery code as:
   1: data: "{'param1': 1}"
With the above line I would be sending a parameter with value as 1 to the server side method.
The method would change as:
   1: [WebMethod]
   2:    public static string ServerSideMethod(string param1)
   3:    {
   4:        return "Message from server with parameter:"+param1;
   5:    }
The output will now be:
Message from server with parameter:1
You could also call any webmethod method in your webservice by changing the url in the jQuery as:
   1: url: "WebService1.asmx/ServerSideMethod"
where WebService1 is your webservice and ServerSideMethod is your webmethod in WebService1.
Recently I have seen a lot of questions from members in the asp.net forums asking about how to call Javascript confirm on button click and then based on user selection ie Yes/No process code behind logic.
Here is another example of how to do so:
   1: function MyConfirmMethod() {
   2:         if (confirm('Are your sure?')) {
   3:             $.ajax({
   4:                 type: "POST",
   5:                 url: "WebForm1.aspx/ServerSideMethod",
   6:                 data: "{}",
   7:                 contentType: "application/json; charset=utf-8",
   8:                 dataType: "json",
   9:                 success: function (msg) {
  10:                     $('#myDiv').text(msg.d);
  11:                 }
  12:             });
  13:             return false;
  14:         }
  15:         else {
  16:             return false;
  17:         }
  18:     }
   1: protected void Page_Load(object sender, EventArgs e)
   2:   {
   3:       Button1.Attributes.Add("onclick", "return MyConfirmMethod();");
   4:   }
   5:   [WebMethod]
   6:   public static string ServerSideMethod()
   7:   {
   8:       return "Message from server!";
   9:   }




Examples



Recent Post

Parallel Task in .Net 4.0