The factory design pattern consists in a class responsible for creating instances of the requested types. It solves the problem of having decisions all over the place to decide what type it should create.

For example, if we have an application that needs different logic depending on a configuration we can isolate the place where the decision is made:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace ConsoleApplication1
  4. {
  5. public static class AppConfig
  6. {
  7. public static string SiteName = "MangaFox";
  8. // or MangaAccess
  9. }
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. var factory = new MangaReaderFactory();
  15. // request an instance for the current config
  16. MangaReader reader = factory.Create();
  17. // no decision taking, just plain logic
  18. reader.GetChapters();
  19. reader.GetPages(0);
  20. Console.ReadKey(true);
  21. }
  22. }
  23. public class MangaReaderFactory
  24. {
  25. public MangaReader Create()
  26. {
  27. // an instance will be chosen accordingly to the config
  28. switch (AppConfig.SiteName)
  29. {
  30. case "MangaFox":
  31. return new MangaFox();
  32. case "MangaAccess":
  33. return new MangaAccess();
  34. }
  35. throw new ArgumentException("Invalid site name"
  36. , "SiteName");
  37. }
  38. }
  39. public abstract class MangaReader
  40. {
  41. public abstract IEnumerable<string> GetChapters();
  42. public abstract IEnumerable<string> GetPages(int ch);
  43. }
  44. // specific logic for MangaFox
  45. public class MangaFox : MangaReader
  46. {
  47. public override IEnumerable<string> GetChapters()
  48. {
  49. throw new NotImplementedException();
  50. }
  51. public override IEnumerable<string> GetPages(int ch)
  52. {
  53. throw new NotImplementedException();
  54. }
  55. }
  56. // specific logic for MangaAccess
  57. public class MangaAccess : MangaReader
  58. {
  59. public override IEnumerable<string> GetChapters()
  60. {
  61. throw new NotImplementedException();
  62. }
  63. public override IEnumerable<string> GetPages(int ch)
  64. {
  65. throw new NotImplementedException();
  66. }
  67. }
  68. }
Without the Factory you would have to take decisions directly on your code, or decide which instance to create without a central place to take care of that for you.