One software can have multiple versions and each version may provide different methods. If you want to make available of latest version for your client, he may need to change lot of code at client side and some clients may still want to call old version only. These type of problems will solved by Bridge Design patterns.
Bridge design pattern in C# useful when new version of particular is developed, but still old version needs to be run for some clients. By using Bridge pattern client no need change any code to call newer version of software, just he has to pass the version details.
For example, we have some payment gateway where client will call to connect to some banks for paying the bills. Tomorrow a new bank may add to the Payment gateway application for some clients. By adding this new bank will not affect existing clients, it enable the new clients to call the new bank. We can achieve this by using Bridge Design Pattern.
Bridge Pattern in C# has one Abstract Class(which called by the client), One Interface( Abstract Class expects this interface as parameter from client) and any number of Implemented classes based on our requirements which implements the interface.
Let's take payment gateway example, first create interface which has to implemented by implementation classes as shown below.
public interface PayInterface
{
string BankMethod();
}
class BankA:PayInterface
{
#region PayInterface Members
public string BankMethod()
{
return "Bank A is calling";
}
#endregion
}
class BankB:PayInterface
{
#region PayInterface Members
public string BankMethod()
{
return "Bank B is calling";
}
#endregion
}
As shown above PayInterface is interface, BankA and BankB are the implementation classes which implements the interface PayInterface. Now implement Abstraction class for which client passes the version.
public class Pay
{
PayInterface pi;
public Pay(PayInterface payInterface)
{
pi = payInterface;
}
public string Banker()
{
return "Bridge Pattern: " + pi.BankMethod();
}
}
As shown above Pay is the Abstraction class and its parameterized constructor expects the interface PayInterface. Pay class has the Banker method to display which implementation client calls.
Lets write the client code to call the above Payment gateway application as shown below.
static void Main(string[] args)
{
//calling Bank A
Console.WriteLine(new Pay(new BankA()).Banker());
//calling Bank B
Console.WriteLine(new Pay(new BankB()).Banker());
Console.ReadLine();
}
As shown above, each time client passing the implementation name to call the proper version. The output of the client is given below.