Factory Design Pattern in C#

 

Factory Design Pattern is the one of the Creational pattern and it is very useful to restrict the client from knowing which class he is calling. That means if there are several class with  same behaviour, then based on your flexibility you can provide one of the class to interface through interface. SO client does not know which class he is calling.

 

For example many web sites provides the payment gateway(Paypal, CCAvenue....etc) to sell their products. Here web site owner don't know which bank payment gateway is using. They exposes all payment procedure through some interface. Here Factory Design Pattern is very useful.

 

Today we discuss about Factory Design Pattern in C# with example. For example we have some API to log to log the errors or user activity, but client should not know in which data source we are logging the error. In this type of scenario Factory Design Pattern is very useful.

 

The basic components of Factory Design Pattern are one interface, classes which implements the interface(here two classes one for XML Source and another for SQL Source), Factory class which has method to return object, method in the Factory Class returns the object through interface based on user input and finally enumeration to facilitates the user for input.

 

Interface Components: ISource

Main Classes which implements interface: XMLSource, SQLSource

Factory Class which provides object for Client: SourceFactory

Factory Class Method to return object: GetSource()

Enumeration for input(Optional):  EnumSource

 

Let's implement Factory Design Pattern in C# by using above components.

 

Open Microsoft Visual Studio => Create Console Application with name as FactoryDesignPatternCSharp.

 

Create interface ISource with Pay()  method as shown below.

 

namespace FactoryDesignPatternCSharp

{

    interface ISource

    {

        void Save();

    }

}

 

Create sources classes XMLSource.cs and SQLSource.cs by implementing the ISource as shown below.

 

using System;

 

namespace FactoryDesignPatternCSharp

{

    class XMLSource:ISource

    {

        #region ISource Members

 

        public void Save()

        {

            Console.WriteLine("This is From XML Source");

        }

 

        #endregion

    }

}

 

 

using System;

 

namespace FactoryDesignPatternCSharp

{

    class SQLSource:ISource

    {

        #region ISource Members

 

        public void Save()

        {

            Console.WriteLine("This is From SQL Source");

        }


        #endregion

    }

}

 

Now create the Factory class which provides the object to client based on user input, for user input create enumeration EnumSource as shown below.

 

namespace FactoryDesignPatternCSharp

{

    enum EnumSource

    {

        XMLSource,

        SQLSOurce

    }

}

 

 

namespace FactoryDesignPatternCSharp

{

    class SourceFactory

    {

        public static ISource GetSource(EnumSource eSource)

        {

            ISource iSource = null;

 

            if (eSource == EnumSource.XMLSource)

            {

                iSource = new XMLSource();

            }

            else if (eSource == EnumSource.SQLSOurce)

            {

                iSource = new SQLSource();

            }


            return iSource;

        }

    }

}

 

As shown above GetSource() method returns the source object based on user input.  As discussed here client does not know for which class client creating the object because it returns object in the form of interface ISource.

 

Now call the above application from client side as shown below.

 

 

using System;

 

namespace FactoryDesignPatternCSharp

{

    class Program

    {

        static void Main(string[] args)

        {

            ////call SourceFactory by passing your required source, for exampe XML Source

            //ISource iSource = SourceFactory.GetSource(EnumSource.XMLSource);

            //iSource.Save();

 

            //call SourceFactory by passing your required source, for exampe SQL Source

            ISource iSource = SourceFactory.GetSource(EnumSource.SQLSOurce);

            iSource.Save();

 

            Console.ReadLine();

        }

    }

}

 

As shown above we are calling the GetSource() method of SourceFactory() class to get the object. Here if you observe client does not know whether he is calling XMLSource or SQLSource, client knows only interface ISource.

 

Run the application, the output is as shown below.

 

            

 

Factory Design Pattern is not only useful to hide the creation of object, it also allows us to add more number classes without knowing client. In above example as of now e have only XMLSource and SQLSource, in future we can add new data source like logging in notepad or in Access database for new users. Because of adding new source client no need to change any of his logic, just he has to pass required source type through enumeration. In this way we can avoid re-designing our application for future enhancements.

 

                                                                                                   FactoryDesignPatternCSharp.zip (27.73 kb)