Factory Pattern

The factory method pattern is an object-oriented design pattern. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify thederived type of product that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.

EXAMPLE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace Army
{
    interface ISoldier
    {
        int Rank();
    }
 
    abstract class Soldier : ISoldier
    {
        public abstract int Rank();
    }
 
    class Infantry : Soldier
    {
        override
        public int Rank()
        {
            return 1;
        }
    }
 
    class Marine : Soldier
    {
        override
        public int Rank()
        {
            return 2;
        }
    }
 
    class Commando : Soldier
    {
        override
        public int Rank()
        {
            return 3;
        }
    }
 
    class HeadQuarter
    {
        public enum SoldierType
        {
            Infantry,
            Marine,
            Commando
        }
 
        public static ISoldier createSoldier(SoldierType soldierType)
        {
            switch (soldierType)
            {
                case SoldierType.Infantry:
                    return new Infantry();
                case SoldierType.Marine:
                    return new Marine();
                case SoldierType.Commando:
                    return new Commando();
            }
            throw new ArgumentException("The soldier type " + soldierType + " is not recognized.");
        }
    }
 
    class Troops
    {
        public static void Main(string[] args)
        {
 
            HeadQuarter.SoldierType[] soldierTypes = { HeadQuarter.SoldierType.Commando,
                                                HeadQuarter.SoldierType.Infantry,
                                                HeadQuarter.SoldierType.Marine};
            foreach (HeadQuarter.SoldierType soldierType in soldierTypes)
            {
                System.Console.WriteLine("Rank of " + soldierType + " is " +
                    HeadQuarter.createSoldier(soldierType).Rank());
            }
        }
    }
 
    //Output:
    //Rank of Commando is 3
    //Rank of Infantry is 1
    //rank of Marine is 2
}