Singleton.cs 2.3 KB

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