Sunday, January 26, 2014

Factory Method Pattern

The factory method pattern defines an interface for creating an object, but let subclasses decide which class to instantiate.

Example:

//Create the interface
    public interface iEmployee
    {
        void display(string FirstName, string LastName);
    }


    //Create the Employee Class and Implement the iEmployee Interface
    public class Employee : iEmployee
    {

        public void display(string FirstName, string LastName)
        {
            Console.WriteLine(FirstName +' '+ LastName );
        }

    }

    //Create the abstract EmployeeFactory Class.
    //Create GetEmployeeFactory method with return type of interface (iEmployee).
    public abstract class EmployeeFactory
    {
        public abstract iEmployee GetEmployeeFactory();
   
    }


    //Inherit and Implement the abstract EmployeeFactory class.
    //Override the abstract GetEmployeeFactory method.
    public class EmployeeList : EmployeeFactory
    {

        public override iEmployee GetEmployeeFactory()
        {
            return new Employee();

        }


    }

static void Main(string[] args)
        {

            EmployeeFactory obj = new EmployeeList();
            iEmployee iObj = obj.GetEmployeeFactory();

            iObj.display("Factory", "Method");
               
            Console.ReadLine();
        }

    }

1 comment:

Abstract Factory Vs Factory Method

Abstract Factory Provides an interface for creating families of related or dependent objects without specifying their concrete classes ...