Factory Method

0

Category : ,

The Factory completely hides/removes the process of creating objects from the client/caller.

Example

Lets say we have an eCommerce application and we have 2 payment gateways integrated with our application. Lets call these payment gateways BankOne and BankTwo.

Interface

We need a "Payment Gateway" interface to set the template/functionality that all payment gateways need to provide.

interface IPaymentGateway
{
    void MakePayment(Product product);        
}

Concrete implementations

Concrete implementations of Payment Gateways required:
public class BankOne : IPaymentGateway
{
    public void MakePayment(Product product)
    {
        // The bank specific API call to make the payment
        Console.WriteLine("Using bank1 to pay for {0}, amount {1}", product.Name, product.Price);
    }
}

public class BankTwo : IPaymentGateway
{
    public void MakePayment(Product product)
    {
        // The bank specific API call to make the payment
        Console.WriteLine("Using bank2 to pay for {0}, amount {1}", product.Name, product.Price);
    }
}
To be able to identify what payment mechanism has been selected, lets define a simple Enum PaymentMethod.
enum PaymentMethod
{
    BANK_ONE,
    BANK_TWO
}

Factory

Factory class to handle all the details of creating these objects.
public class PaymentGatewayFactory
{
    public virtual IPaymentGateway CreatePaymentGateway(PaymentMethod method, Product product)
    {
        IPaymentGateway gateway = null;

        switch(method)
        {
            case PaymentMethod.BANK_ONE:
                gateway = new BankOne();
                break;
            case PaymentMethod.BANK_TWO:
                gateway = new BankTwo();
                break;
        }

        return gateway;
    }
}
Our factory class accepts the selected payment gateway and then based on the selection it is creating the concrete payment gateway class. We have effectively abstracted out all these details from the client code. Otherwise every class that want to use a payment gateway would have to write all this logic.

Usage

Lets now look at how the client class can use this factory method to make the payment.
public class PaymentProcessor
{
    IPaymentGateway gateway = null;

    public void MakePayment(PaymentMethod method, Product product)
    {
        PaymentGatewayFactory factory = new PaymentGatewayFactory();
        this.gateway = factory.CreatePaymentGateway(method, product);

        this.gateway.MakePayment(product);
    }
}
Now our client class does not depend on the concrete payment gateway classes. It also does not have to worry about the creation logic of the concrete payment gateway classes. All this is nicely abstracted out in the factory class itself.


my thanks to the following article:
https://www.codeproject.com/Articles/874246/Understanding-and-Implementing-Factory-Pattern-i

0 comments:

Post a Comment