Wednesday, July 20, 2016

Bridge Pattern


Bridge pattern acts as an intermediary between two interfaces. Bridge Pattern falls under structural pattern of GOF (Gang of Four) pattern.

When to use –


Bridge pattern can be used to keep an abstraction separate from its implementation so you can change both abstraction and implementation independently without changing the client code.

Major components of Bridge pattern –


Abstraction – This is an abstract class provides abstraction to the clients.
Refined Abstraction – This class will implement the abstract class.
Implementer – This interface will act as bridge between abstraction and implementer classes and also define common functionality of implementer.
Concrete Implementer – Implements the implementer interface and defines its concrete implementation.

Let’s have a look on below code demonstrating bridge pattern.

Code –
//abstraction
public abstract class Switch
{
    public abstract void TurnOn();
    public abstract void TurnOff();
    protected IDevice device;
}

//refined abstraction
public class RemoteControl : Switch
{
    IDevice myDevice;
    public RemoteControl(IDevice device)
    {
        myDevice = device;
    }
    public override void TurnOn()
    {
        myDevice.TurnOn("Remote Control");
    }

    public override void TurnOff()
    {
        myDevice.TurnOff("Remote Control");
    }
}
//refined abstraction
public class ManualSwitchBoard : Switch
{
    IDevice myDevice;
    public ManualSwitchBoard(IDevice device)
    {
        myDevice = device;
    }
    public override void TurnOff()
    {
        myDevice.TurnOff("Manual Switch Board");
    }

    public override void TurnOn()
    {
        myDevice.TurnOn("Manual Switch Board");
    }
}
   
//implementer - Bridge interface
public interface IDevice
{
    void TurnOn(string input);
    void TurnOff(string input);
}
//concrete implementer
public class TV : IDevice
{
    public void TurnOff(string input)
    {
        Console.WriteLine("Turning off TV via {0}", input);
    }

    public void TurnOn(string input)
    {
        Console.WriteLine("Turning on TV via {0}", input);
    }
}
//concrete implementer
public class Fan : IDevice
{
    public void TurnOn(string input)
    {
        Console.WriteLine("Turning on Fan via {0}", input);
    }

    public void TurnOff(string input)
    {
        Console.WriteLine("Turning off Fan via {0}", input);
    }
}
//client
class Program
{
    static void Main(string[] args)
    {
        //Implementation objects
        IDevice TV = new TV();
        IDevice Fan = new Fan();

        //abstraction objects
        Switch TVSwitch = new RemoteControl(TV);
        Switch FanSwitch = new RemoteControl(Fan);

        //client calls abstration object methods to achieve functionality
        TVSwitch.TurnOn();
        FanSwitch.TurnOn();
        TVSwitch.TurnOff();
        FanSwitch.TurnOff();

        TVSwitch = new ManualSwitchBoard(TV);
        TVSwitch.TurnOn();
        TVSwitch.TurnOff();

        Console.ReadLine();
    }
}

Output –



Above example provides multiple ways to turn on and turn off multiple devices. You can add as many devices as you want and you can also implement more methods to turn on and turn off devices. As per above example, Switch is abstract class and inherited by multiple classes and IDevice is an interface and act as Bridge and multiple devices implemented IDevice interface to achieve implementation part of how device work. Client needs to call only abstraction objects to achieve its functionality. As per above code, TV can be turn on or off via remote control or manually via switch board. If TV/Fan turning on/off mechanism changed then it won’t impact client code.

Advantages –

  • Abstraction and implementation can be changed independently.
  • Abstraction and implementer hierarchies can be extended independently.
  • Hides implementation details from Client.

Difference between Adapter Pattern and Bridge Pattern –


Adapter Pattern
Bridge Pattern
Adapter pattern used to work with two incompatible interfaces
Bridge pattern provides multiple ways to design different components with multiple implementation. It allows to change abstraction and implementation separately.
Adapter pattern can be used on already designed objects.
Bridge pattern can be used on objects at the time of design.


I hope this article helps you to know more about Bridge Pattern. Please leave your feedback in comments below.


References –

See Also –


Sunday, July 10, 2016

How to create an instance of class dynamically and invoke method?

Normally we create instance of class using new keyword followed by class name. In below example new instance of “TestClass” is created using new keyword.

TestClass test = new TestClass();

But if you want to create an instance of class dynamically from assembly, how you can do it? You can do it using reflection by calling Activator.CreateInstance method. Activator class is part of System namespace. See below example how Activator.CreateInstance method used to create an instance of type.

namespace TestLibrary
{
    public class TestFile
    {
        public void DisplayFileName(string fileName)
        {
            Console.WriteLine("File Name :- {0}", fileName);
        }
    }
}




"TestLibrary" class library project added to console application and created above mentioned "TestFile" class and added reference of "TestLibrary" project to console application.  See below code from console application to dynamically create an instance of "TestFile" class and invoke "DisplayFileName" method.

Code -
public class Program
{
    static void Main(string[] args)
    {
        //Loads Assembly
        Assembly assembly = Assembly.Load("TestLibrary");
        //Gets type which object you wants to create
        Type t = assembly.GetType("TestLibrary.TestFile");
        //creates an instance of given type
        object obj = Activator.CreateInstance(t);
        //parameters for method
        object[] parameters = new object[] {"Binary File"};
        //Invokes method of class
        t.InvokeMember("DisplayFileName", BindingFlags.InvokeMethod, null, obj, parameters);

        Console.ReadLine();
    }
}


Output - 









In above example, an instance of “TestFile” class (of different assembly) is created and invoked “DisplayFileName” method dynamically.

First you need to load “TestLibrary” assembly using Assembly.Load method. You need to add reference of “TestLibrary” assembly in your application. If you want to load other assembly which is not referenced in your project, then you can use Assembly.LoadFile method to load external assembly. After successfully loading assembly, you need to load class using Assembly.Gettype instance method and create instance of that class using Activator.CreateInstance method. Once you get an instance of “TestFile” class, you can invoke “DisplayFileName” method via type InvokeMemeber method. The whole process is done dynamically via Reflection.

After reading this article, I hope you have more understating about how you can create an instance of class and invoke method dynamically via reflection. Please leave your feedback in comments below.

References –

See Also –

Wednesday, July 6, 2016

How to set default value to auto properties in C#?

There are many ways to initialize properties with default value. The most common way to set default value of any property is to set its local variable with default value. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    private int age = 25;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

}

Output –
Age - 25

But when you are using auto-properties you don’t need to declare local variable for it since it’s internally taken care by CLR. So how to set default value to auto-properties? There is a way, you can set default value to auto-property using DefaultValue attribute. DefaultValue attribute is part of System.ComponentModel namespace. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    //DefaultValue Attribute to set Default Value of Age property
    [DefaultValue(35)]
    public int Age { get; set; }

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        //This method sets value for all the properties reading from DefaultValue attribute
        InitializeDefaultProperties(this);
           
        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

    public static void InitializeDefaultProperties(object obj)
    {
        foreach (PropertyInfo prop in obj.GetType().GetProperties())
        {
            foreach (Attribute attr in prop.GetCustomAttributes(true))
            {
                if (attr is DefaultValueAttribute)
                    prop.SetValue(obj, ((DefaultValueAttribute)attr).Value, null);
            }
        }
    }
}

Output –
Age - 35

As you can see in above example, Age property is decorated with DefaultValue attribute. DefaultValue attribute will not automatically set Property value. You need to manually set its value in constructor using refection. The good part of initializing value of property using Default Value is more consistent with design and less error prone. Since this approach involves reflection, this is not very efficient way to set default value to properties.

With C# 6.0, you can set default value to auto-properties even more better and easiest way. See below code.

Code - 
public partial class DefaultValueProperties : Window
{
    public int Age { get; set; } = 30;

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }
}

Output –
Age - 30


Hope you liked this article. Your feedback/comments are most welcome. Happy reading. J


References –

See Also –


Saturday, July 2, 2016

Adapter Pattern


Adapter pattern enables application to use classes or interfaces which are not matching its requirement. Adapter pattern falls under structural pattern of GOF (Gang of Four) pattern.

When to use –


Adapter pattern can be used when you want to utilize third party API which is not compatible or mismatching your current implementation. You want to use third party API in your application but your application doesn’t understand the object of third party API in such scenarios, you need to use Adapter pattern to create wrapper class which contains code to utilize third party API. You can also consider to use adapter pattern when you have an existing system and you want to use some features of new application but interfaces are different.

There are so many real world example of adapter pattern but most common is power adapter. India’s power socket and plug is different from America’s power socket and plug. To use any Indian electronic appliances in America, you need an adapter (universal power adapter) which allows India’s plug to fit in America’s power socket. In .net world SQLAdapter, OracleAdapter are good example of adapter pattern.

Major components of Adapter pattern –

  • ITarget – This is an interface which client wants to use to achieve its functionality.
  • Adapter – This class implement ITarget interface and responsible for providing functionality that client wants and communicates with Adaptee class.
  • Adaptee – This class has actual functionality that client wants but its interface is not compatible with client.
  • Client – This class want to achieve functionality that Adaptee class has but via ITarget interface due to incompatible interfaces.

Let’s have a look on below code demonstrating adapter pattern.

Code –

public enum TransactionType
{
    Cash,
    NetBanking,
    CreditCard
}
//ITarget - Target interface
public interface IPayment
{
    void PayAmount(TransactionType type, double amount);
}
//Adapter class - integrates with Adaptee
public class PaymentGatewayAdapter : IPayment
{
    public void PayAmount(TransactionType type, double amount)
    {
        PayPalPaymentGateway payPalGateway = new PayPalPaymentGateway();
        switch (type)
        {
            case TransactionType.Cash:
                payPalGateway.PayCash(amount);
                break;
            case TransactionType.NetBanking:
                payPalGateway.PayViaNetBanking(amount);
                break;
            case TransactionType.CreditCard:
                payPalGateway.PayViaCard(amount);
                break;
            default:
                break;
        }
    }
}

//Adaptee – Third party API
public class PayPalPaymentGateway
{
    public void PayCash(double amount)
    {
        Console.WriteLine("Cash payment successful for amount {0}", amount);
    }
    public void PayViaCard(double amount)
    {
        Console.WriteLine("Card payment successful for amount {0}", amount);
    }
    public void PayViaNetBanking(double amount)
    {
        Console.WriteLine("Net Banking payment successful for amount {0}", amount);
    }
}

//Client
class Program
{
    static void Main(string[] args)
    {
        IPayment paymentGateway = new PaymentGatewayAdapter();
        paymentGateway.PayAmount(TransactionType.NetBanking, 2000);
        Console.ReadLine();
    }
}

Output –



As you can see in above example, PaypalPaymentGateway class is third party API which can directly be used by client to make payments but application has some different implementation and client doesn't want to change it and which is not matching with Third party API. In above example, third party API has different methods for different types of payments. PaymentGatewayAdapter class has adopted third party API differences and returned functionality that client wanted. This example is very simple but actual implementation of Adapter class may be more complex than this based on third party API object and client requirement.

In above example, if PayPal payment gateway renames its ‘PayCash’ method or any other method then client doesn’t need to change anything only change in Adapter class. Similarly, if you decide to use some other payment gateway instead of PayPal you don’t need to change client side implementation just change in Adapter class to integrate with new payment gateway interface.

I hope this article helps you to understand more about Adapter Pattern. Please leave your feedback in comments below.

References –

See Also –