Singleton.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3. * Version: GPL 2.0
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License. You should have
  7. * received a copy of the GPL license along with this program; if you
  8. * did not, you can find it at http://www.gnu.org/
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. *
  15. * The Original Code is Coreseek.com code.
  16. *
  17. * Copyright (C) 2007-2008. All Rights Reserved.
  18. *
  19. * Author:
  20. * Li monan <li.monan@gmail.com>
  21. *
  22. * ***** END LICENSE BLOCK ***** */
  23. #ifndef CSR_SINGLETON_H
  24. #define CSR_SINGLETON_H
  25. #ifdef HAVE_ATEXIT
  26. #ifdef HAVE_CSTDLIB
  27. #include <cstdlib>
  28. using std::atexit;
  29. #else
  30. #include <stdlib.h>
  31. #endif
  32. #endif
  33. /**
  34. * A template class that implements the Singleton pattern.
  35. * FIXME: should I impl HAVE_ATEXIT mode? like bzflag?
  36. */
  37. template <typename T>
  38. class CSR_Singleton {
  39. static T* ms_instance;
  40. public:
  41. /**
  42. * Static method to access the only pointer of this instance.
  43. * \return a pointer to the only instance of this
  44. */
  45. static T* Get();
  46. /**
  47. * Release resources.
  48. */
  49. static void Free();
  50. protected:
  51. /**
  52. * Default constructor.
  53. */
  54. CSR_Singleton();
  55. /**
  56. * Destructor.
  57. */
  58. virtual ~CSR_Singleton();
  59. static void destroy() {
  60. if (ms_instance != 0) {
  61. delete (ms_instance);
  62. ms_instance = 0;
  63. }
  64. }
  65. };
  66. template <typename T>
  67. T* CSR_Singleton<T>::ms_instance = 0;
  68. template <typename T>
  69. CSR_Singleton<T>::CSR_Singleton() {}
  70. template <typename T>
  71. CSR_Singleton<T>::~CSR_Singleton() {}
  72. template <typename T>
  73. T* CSR_Singleton<T>::Get() {
  74. if (!ms_instance) {
  75. ms_instance = new T();
  76. // destroy the singleton when the application terminates
  77. #ifdef HAVE_ATEXIT
  78. atexit(CSR_Singleton::destroy);
  79. #endif
  80. }
  81. return ms_instance;
  82. }
  83. template <typename T>
  84. void CSR_Singleton<T>::Free() {
  85. if (ms_instance) {
  86. delete ms_instance;
  87. ms_instance = 0;
  88. }
  89. }
  90. #endif // CSR_SINGLETON_H