Wednesday, 11 July 2018

Bridge Design Pattern - Structural

Separates an interface from its implementation. Uses encapsulation, aggregation and uses inheritance to separate responsibilities.

Sample Code Download: BridgeDesignPattern.zip (Visual Studio 2017 Console App)

Create an interface IPaymentSystem to ProcessPayment

public interface IPaymentSystem
{
    void ProcessPayment(string paymentSystem);
}


Create Citibank as Paymentgateway and implement ProcessPayment 

public class CitiPaymentSystem : IPaymentSystem
{
    public void ProcessPayment(string paymentSystem)
    {
        Console.WriteLine("Using CitiBank gateway for  " + paymentSystem);
    }
}

Create IDBI as Payment gateway and implement ProcessPayment

public class IDBIPaymentSystem : IPaymentSystem
{
    public void ProcessPayment(string paymentSystem)
    {
        Console.WriteLine("Using IDBIBank gateway for  " + paymentSystem);
    }
}

Though we are processing payments using different payment gateways, Now a point to note here is that, for the end customer, the only that that matters is whether it’s Net banking or Credit/Debit card payment.

Which means we need to use these payment gateways and bridge them with Net Banking or Credit/Debit cards.

Let’s proceed and create those Classes of Abstraction and Refined Abstraction implementations.

public abstract class Payment
{
    public IPaymentSystem _IPaymentSystem;
    public abstract void MakePayment();
}

Create Refined abstraction class Card Payment and inherit the abstract class Payment 

public class CardPayment : Payment
{
    public override void MakePayment()
    {
        _IPaymentSystem.ProcessPayment("Card Payment");
    }
}

Create Refined abstraction class Net Banking Payment and inherit the abstract class Payment 

public class NetBankingPayment : Payment
{
    public override void MakePayment()
    {
        _IPaymentSystem.ProcessPayment("NetBanking Payment");
    }
}

Switch to the client which is main program and implement the below code

class Program
{
    static void Main(string[] args)
    {
        Payment order = new CardPayment();
        order._IPaymentSystem = new CitiPaymentSystem();
        order.MakePayment();

        order._IPaymentSystem = new IDBIPaymentSystem();
        order.MakePayment();

        order = new NetBankingPayment();
        order._IPaymentSystem = new CitiPaymentSystem();
        order.MakePayment();

        Console.ReadLine();
    }
}




Structural Design Patterns   Adapter | Bridge | Composite | Decorator | Facade | Flyweight | Proxy