Singleton.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. namespace Quadarax.Foundation.Common.Object
  2. {
  3. namespace Bee.Core.Pattern
  4. {
  5. /// <summary>
  6. /// Well-known singleton pattern implementation.
  7. /// </summary>
  8. /// <remarks>
  9. /// The singleton type must inherit this class. The actual instance type is determined
  10. /// by the only type parameter. The singleton type must implement a default constructor.
  11. /// </remarks>
  12. /// <typeparam name="TInstance"></typeparam>
  13. public class Singleton<TInstance> where TInstance : class, new()
  14. {
  15. private static volatile TInstance _instance;
  16. private static readonly object _syncRoot = new object();
  17. /// <summary>
  18. /// Singleton instance
  19. /// </summary>
  20. public static TInstance Instance
  21. {
  22. get
  23. {
  24. if (_instance == null)
  25. {
  26. lock (_syncRoot)
  27. {
  28. if (_instance == null)
  29. _instance = new TInstance();
  30. }
  31. }
  32. return _instance;
  33. }
  34. }
  35. }
  36. /// <summary>
  37. /// Well-known singleton pattern implementation.
  38. /// </summary>
  39. /// <remarks>
  40. /// The singleton type must inherit this class. The actual instance type is determined
  41. /// by the only type parameter. The singleton type must implement a default constructor.
  42. /// </remarks>
  43. /// <typeparam name="TInstance"></typeparam>
  44. /// <typeparam name="TInterface"></typeparam>
  45. public class Singleton<TInterface, TInstance>
  46. where TInstance : TInterface, new()
  47. where TInterface : class
  48. {
  49. private static volatile TInterface _instance;
  50. private static readonly object _syncRoot = new object();
  51. public static TInterface Instance
  52. {
  53. get
  54. {
  55. if (_instance == null)
  56. {
  57. lock (_syncRoot)
  58. {
  59. if (_instance == null)
  60. _instance = new TInstance();
  61. }
  62. }
  63. return _instance;
  64. }
  65. }
  66. }
  67. }
  68. }