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:
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 Instance1: IInstance { public void Print() { Console.WriteLine(ToString()); Console.ReadLine(); } }
public class Instance2: IInstance { public void Print() { Console.WriteLine(ToString()); Console.ReadLine(); } }public class Instance3: IInstance { 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 Factory: IFactory { private int Index { get; set; } 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!