Friday, June 14, 2013

Factory Design pattern

Factory design pattern is one of the common design pattern  in software project. Let’s understand the basic of Factory design patern.
Before start discussion Let’s learn the advantage of Factory design pattern.  And obviously those are the reason to implement Factory design patern.

1)      In client here and there we create object using new keyword within much more if – else condition . If you implement factory design pattern to reduce new keyword in client.

2)      When you want to abstract your business class from client ,then implement factory pattern in your project in project.

In below code it will show how to implement factory design pattern in project. Here I have two types of employee class in my code and I have created a factory class EmployeeFactory to supply object of appropriate class depending upon class request . Now if you add one more type of employee class in your nosiness logic the client should not bother at all. Just tell your client to send proper code to get object of newly added class.
So basically our factory class is making am abstraction over our business class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;

namespace BlogProject
{
    // Factory Design patern
    public interface IEmployee
    {
        void ShowEmployee();
    }
    public class Developer:IEmployee
    {
        public void ShowEmployee()
        {
            Console.Write("I ma .NET Developer");
        }
    }

    public class HR : IEmployee
    {
        public void ShowEmployee()
        {
            Console.Write("I am Technical HR");
        }
    }

    public class EmployeeFactory
    {
        // Factory class to generate object of concrite class
        public IEmployee GetObject(int a)
        {
            if (a == 1)
            {
                return new Developer();
            }
            else if (a == 2)
            {
                return new HR();
            }
            else
                return null;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter 1 to create Developer class object and 2 to create HR class object"+"\n");
            int Type = Convert.ToInt32(Console.ReadLine());
            EmployeeFactory objFactory = new EmployeeFactory();
            IEmployee objemp = objFactory.GetObject(Type);
            objemp.ShowEmployee();
            Console.ReadLine();
        }
    }
}




No comments:

Post a Comment