A factory method allows for an easy way to create objects when multiple classes are involved. It eases the way of object creation but allows the subclass to decide which object needs to be created.
It would be tedious when the client needs to specify the class name while creating the objects. So, to resolve this problem, we can use Factory pattern.
A Simple factory pattern Sample
- using System;
-
- class Program
- {
- abstract class Animal
- {
- public abstract string Title { get; }
- }
-
- class Dog : Animal
- {
- public override string Title
- {
- get
- {
- return "Dog";
- }
- }
- }
-
- class Cat : Animal
- {
- public override string Title
- {
- get
- {
- return "Cat";
- }
- }
- }
-
- class Fish : Animal
- {
- public override string Title
- {
- get
- {
- return "Fish";
- }
- }
- }
-
- static class Factory
- {
- public static Animal Get(int id)
- {
- switch (id)
- {
- case 0:
- return new Dog();
- case 1:
- case 2:
- return new Cat();
- case 3:
- default:
- return new Fish();
- }
- }
-
-
- static void Main()
- {
- for (int i = 0; i <= 3; i++)
- {
- var position = Factory.Get(i);
- Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
-
- }
- Console.ReadLine();
- }
- }
- }
Now, in case we have many objects, then we need to write multiple Switch cases. We can avoid multiple Switch case by using a dictionary returning a delegate.
Factory pattern without Switch case
- using System;
- using System.Collections.Generic;
-
- class Program
- {
- public abstract class Animal
- {
- public abstract string Title { get; }
- }
-
- public class Dog : Animal
- {
- public override string Title
- {
- get
- {
- return "Dog";
- }
- }
- }
-
- public class Cat : Animal
- {
- public override string Title
- {
- get
- {
- return "Cat";
- }
- }
- }
-
- public class Fish : Animal
- {
- public override string Title
- {
- get
- {
- return "Fish";
- }
- }
- }
-
- public static class Factory
- {
-
- public static Animal Get(int id)
- {
- var factory = cardFactories[id];
- return factory();
- }
-
-
- public static Dictionary<int, Func<Animal>> cardFactories =
- new Dictionary<int, Func<Animal>>
- {
- { 0, ()=>new Dog() },
- { 1, ()=>new Cat() },
- { 2, ()=>new Fish() },
-
- };
-
- }
-
- static void Main()
- {
- for (int i = 0; i <= 3; i++)
- {
- var position = Factory.Get(i);
- Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
-
- }
- Console.ReadLine();
- }
- }
It is a neat way that needs fewer lines to code.