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

  1. using System;
  2. class Program
  3. {
  4. abstract class Animal
  5. {
  6. public abstract string Title { get; }
  7. }
  8. class Dog : Animal
  9. {
  10. public override string Title
  11. {
  12. get
  13. {
  14. return "Dog";
  15. }
  16. }
  17. }
  18. class Cat : Animal
  19. {
  20. public override string Title
  21. {
  22. get
  23. {
  24. return "Cat";
  25. }
  26. }
  27. }
  28. class Fish : Animal
  29. {
  30. public override string Title
  31. {
  32. get
  33. {
  34. return "Fish";
  35. }
  36. }
  37. }
  38. static class Factory
  39. {
  40. public static Animal Get(int id)
  41. {
  42. switch (id)
  43. {
  44. case 0:
  45. return new Dog();
  46. case 1:
  47. case 2:
  48. return new Cat();
  49. case 3:
  50. default:
  51. return new Fish();
  52. }
  53. }
  54. static void Main()
  55. {
  56. for (int i = 0; i <= 3; i++)
  57. {
  58. var position = Factory.Get(i);
  59. Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
  60. }
  61. Console.ReadLine();
  62. }
  63. }
  64. }
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
  1. using System;
  2. using System.Collections.Generic;
  3. class Program
  4. {
  5. public abstract class Animal
  6. {
  7. public abstract string Title { get; }
  8. }
  9. public class Dog : Animal
  10. {
  11. public override string Title
  12. {
  13. get
  14. {
  15. return "Dog";
  16. }
  17. }
  18. }
  19. public class Cat : Animal
  20. {
  21. public override string Title
  22. {
  23. get
  24. {
  25. return "Cat";
  26. }
  27. }
  28. }
  29. public class Fish : Animal
  30. {
  31. public override string Title
  32. {
  33. get
  34. {
  35. return "Fish";
  36. }
  37. }
  38. }
  39. public static class Factory
  40. {
  41. public static Animal Get(int id)
  42. {
  43. var factory = cardFactories[id];
  44. return factory();
  45. }
  46. public static Dictionary<int, Func<Animal>> cardFactories =
  47. new Dictionary<int, Func<Animal>>
  48. {
  49. { 0, ()=>new Dog() },
  50. { 1, ()=>new Cat() },
  51. { 2, ()=>new Fish() },
  52. };
  53. }
  54. static void Main()
  55. {
  56. for (int i = 0; i <= 3; i++)
  57. {
  58. var position = Factory.Get(i);
  59. Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
  60. }
  61. Console.ReadLine();
  62. }
  63. }
It is a neat way that needs fewer lines to code.