Factory Design Pattern Real Word Example

Factory pattern is one of the most used design patterns. The Factory pattern is a design pattern used to define a runtime interface for creating an object. It’s called a factory because it creates various types of objects without necessarily knowing what kind of object it creates or how to create it.

The Factory pattern is generally used in the following situations:

  • A class cannot anticipate the type of objects it needs to create beforehand.
  • A class requires its subclasses to specify the objects it creates.
  • You want to localize the logic to instantiate a complex object

This is a pattern of creation of objects and usually I use it to solve the problem that is presented when we have to create the instance of an object but a priori we do not know what type of object has to be, generally, because it depends on some Option that the user selects in the application or because it depends on a configuration that is done at application runtime.

Factory classes are often implemented because they allow the project to follow the SOLID principles more closely. In particular, the interface segregation and dependency inversion principles. Factories and interfaces allow for a lot more long term flexibility. It allows for a more decoupled – and therefore more testable

To understand better the pattern let me show you the following example:

Problem:
We have an online store where the user is offered two different methods of payment: card or paypal.

Solution:

Interface of the type of payments

public interface IPaymentType
    {
        bool IsValidPayment();
        void ProcessPayment();
    }

Card Payment and Paypal Payment

public class CardPayment : IPaymentType
    {

        bool IPaymentType.IsValidPayment()
        {
            Console.WriteLine("Card Payment Valid");
            return true;
        }

        public void ProcessPayment()
        {
            Console.WriteLine("Card Payment Processed");
        }
    }

public class PaypalPayment : IPaymentType
    {
        bool IPaymentType.IsValidPayment()
        {
            Console.WriteLine("Paypal Payment Valid");
            return true;
        }

        public void ProcessPayment()
        {
            Console.WriteLine("Paypal Payment Processed");
        }
    }

Payment Factory that will contain the logic to instantiate one of the concrete class base on some logic

 public class PaymentFactory
    {
        public static IPaymentType GetPaymentType(int paymentTypeId)
        {
            switch (paymentTypeId)
            {
                case 0:
                    return new CardPayment();
                case 1:
                    return new PaypalPayment();
                default:
                    return new CardPayment();
            }
        }
    }

Payment Class that contains a property called “Type” of IPaymentType

public class Payment
    {
        public int Id { get; set; }
        public DateTime Date { get; set; }

        public int TypeId { get; set; }
        public IPaymentType Type { get; set; }
    }

Program to test the implementation

class Program
    {
        static void Main(string[] args)
        {
            //we assumed that  for example the payment type was selected by the user in runtime
            var payment = new Payment()
            {
                Id = 1,
                Date = DateTime.Now,
                TypeId = 1 //paypal
            };

            //Get the correct Payment Type instance in runtime
            payment.Type = PaymentFactory.GetPaymentType(payment.TypeId);

            payment.Type.IsValidPayment();
            payment.Type.ProcessPayment();
            Console.ReadLine();

        }
    }

output

As you can see, if we have to add a new form of payment in the future, we just have to create a new type of payment class and add it as an option to the Payment Factory without modifying the Payment class or the Program/Client itself.

Hope this article has been useful

You can find the code in my Github HERE

Advertisements
This entry was posted in Architecture and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s