Introduction

Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of objects which have common interface.

It will increase the performance of your application is rapidly increased and the cost of the application is free fall.

Example

I’m having many oracle packages, each has many stored procs. Here some of the in parameters are similar to all the packages and also to the stored procs.



In the above diagram shows that each packages has many stored proc’s and each stored proc has many entities.

Here each stored proc has its own in and out parameters but some of the parameters are same for all the stored procs. Now take the common parameters out and create base class with those common entities.
We can implement the above scenario with the below approach.

  1. using System;
  2. /*
  3. * In Factory pattern, we create object without exposing the creation logic.
  4. * In this pattern, an interface is used for creating an object,
  5. * but let subclass decide which class to instantiate.
  6. * */
  7. namespace FactoryMethod
  8. {
  9. Product (abstract)
  10. /*
  11. * Faza Class ITree
  12. *
  13. * */
  14. public interface ITree
  15. {
  16. string GetTreeName();
  17. }
  18. Products (concrete)
  19. /*
  20. * The Concrete class which implements ITree
  21. *
  22. * */
  23. public class BananaTree : ITree
  24. {
  25. public string GetTreeName()
  26. {
  27. return "My Name Is Banana Tree";
  28. }
  29. }
  30. /*
  31. * The Concrete class which implements ITree
  32. *
  33. * */
  34. public class CoconutTree : ITree
  35. {
  36. public string GetTreeName()
  37. {
  38. return "My Name Is Coconut Tree";
  39. }
  40. }
  41. Factory (abstract)
  42. /*
  43. * Faza Class TreeType
  44. * If you want you can add abstract class instad of faza class
  45. *
  46. * */
  47. public interface TreeType
  48. {
  49. ITree GetTree(string tree);
  50. }
  51. Factory (concrete)
  52. /*
  53. * Concrete class which implements faza or concrete class
  54. *
  55. * */
  56. public class ConcreteTreeType : TreeType
  57. {
  58. public ITree GetTree(string tree)
  59. {
  60. if (tree == "COCONUT")
  61. return new CoconutTree();
  62. else
  63. return new BananaTree();
  64. }
  65. }
  66. Client code
  67. /*
  68. * main app.
  69. *
  70. * */
  71. class Program
  72. {
  73. static void Main(string[] args)
  74. {
  75. TreeType oTreeType = new ConcreteTreeType();
  76. ITree banana = oTreeType.GetTree("COCONUT");
  77. Console.WriteLine(banana.GetTreeName());
  78. Console.ReadKey();
  79. }
  80. }}
Conclusion

In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object but let subclass decide which class to instantiate.