Thursday, November 10, 2011

Factory Method Pattern

Very useful pattern, that I am using almost each day - Factory Method Pattern.
I would like to explain it with very simple code that I created for this post:

Before just to image how its looks:



C# Code:

3 Instances that will need to create according to some conditions and we did know before:


 public class Instance1IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }


 public class Instance2IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }


 public class Instance3IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }

All this instances inherits from IInstance interface that have only one PRINT(); method:

 public interface IInstance
    {
        void Print();   
    }

Next - its a Factory class that do all works (concrete of IFactory interface), create one of three above Instance classes according to some condition, in our case its simply swithch caseindex.


 public interface IFactory
    {
        IInstance CreateInstance();
    }



 public class FactoryIFactory
    {
        private int Index { getset; }
 
        public Factory(int instanceIndex)
        {
            Index = instanceIndex;
        }
        public IInstance CreateInstance()
        {
            switch (Index > 2 ? 3 : Index)
            {
                case 1:
                    return new Instance1();                    
                case 2:
                    return new Instance2();
                default:
                    return new Instance3();
            }
        }        


and, main that will run our modest programm:

 static void Main(string[] args)
 {
      IInstance instance = new Factory(2).CreateInstance();
      instance.Print();
 }


Enjoy!























No comments:

Post a Comment