fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Collections;
  7.  
  8.  
  9. namespace PrjObjectPooling
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. Factory fa = new Factory();
  16. Student myStu = fa.GetStudent();
  17. Console.WriteLine("First object");
  18. Student myStu1 = fa.GetStudent();
  19. Console.WriteLine("Second object");
  20. Student myStu2 = fa.GetStudent();
  21. Console.WriteLine("Third object");
  22. Student myStu3 = fa.GetStudent();
  23. Console.WriteLine("Fourth object");
  24. Console.Read();
  25. }
  26. }
  27.  
  28.  
  29. class Factory
  30. {
  31. // Maximum objects allowed!
  32. private static int _PoolMaxSize = 4;
  33. // My Collection Pool
  34. private static readonly Queue objPool = new Queue(_PoolMaxSize);
  35.  
  36. public Student GetStudent()
  37. {
  38. Student oStudent;
  39. // Check from the collection pool. If exists, return object; else, create new
  40. if (Student.ObjectCounter >= _PoolMaxSize && objPool.Count > 0)
  41. {
  42. // Retrieve from pool
  43. oStudent = RetrieveFromPool();
  44. }
  45. else
  46. {
  47. oStudent = GetNewStudent();
  48. }
  49. return oStudent;
  50. }
  51.  
  52. private Student GetNewStudent()
  53. {
  54. // Creates a new Student
  55. Student oStu = new Student();
  56. objPool.Enqueue(oStu);
  57. return oStu;
  58. }
  59.  
  60. protected Student RetrieveFromPool()
  61. {
  62. Student oStu;
  63. // Check if there are any objects in my collection
  64. if (objPool.Count > 0)
  65. {
  66. oStu = (Student)objPool.Dequeue();
  67. Student.ObjectCounter--;
  68. }
  69. else
  70. {
  71. // Return a new object
  72. oStu = new Student();
  73. }
  74. return oStu;
  75. }
  76. }
  77.  
  78. class Student
  79. {
  80. public static int ObjectCounter = 0;
  81. public Student()
  82. {
  83. ++ObjectCounter;
  84. }
  85.  
  86. private string _Firstname;
  87. private string _Lastname;
  88. private int _RollNumber;
  89. private string _Class;
  90.  
  91. public string Firstname
  92. {
  93. get
  94. {
  95. return _Firstname;
  96. }
  97. set
  98. {
  99. _Firstname = value;
  100. }
  101. }
  102.  
  103. public string Lastname
  104. {
  105. get
  106. {
  107. return _Lastname;
  108. }
  109. set
  110. {
  111. _Lastname = value;
  112. }
  113. }
  114.  
  115. public string Class
  116. {
  117. get
  118. {
  119. return _Class;
  120. }
  121. set
  122. {
  123. _Class = value;
  124. }
  125. }
  126.  
  127. public int RollNumber
  128. {
  129. get
  130. {
  131. return _RollNumber;
  132. }
  133. set
  134. {
  135. _RollNumber = value;
  136. }
  137. }
  138. }
  139. }
Success #stdin #stdout 0.02s 15948KB
stdin
Standard input is empty
stdout
First object
Second object
Third object
Fourth object