Singleton.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <stdio.h>
  2. /*
  3. * C++ Design Patterns: SINGLETON
  4. * http://www.plantuml.com/plantuml/uml/LP11ImCn48Nl-HNljeheuhKiIx6856Gzj7V9PeSI66VQJI8KyV_uF_nZpWOhEAVaVUybZrcdxETStjYr3NRRuUdvSVyoe6cTJM2V4dPH3anP1HyEDhUmJ8u1HUAfq6iKkqkW2cykSFkhNbsxJ-T4Cy4d3FVLrOrz5vHrNirwzlp0XVg_Rxgsehvhn_xYtf-Fj5e4R6QozrKyLxPPAX9E9K88HoeP_btZR4fJJ4bKcF2l8kLgdrICboMbKJAcneVm_PLmO1qztpcI2KjljxQJRUW7
  5. *
  6. */
  7. #include <iostream>
  8. #include <string>
  9. class Singleton {
  10. public:
  11. //remove some standard method
  12. //copy constructor and affectation
  13. Singleton(const Singleton&) = delete;
  14. Singleton& operator=(const Singleton&) = delete;
  15. static Singleton* Instance() {
  16. if (!unique_instance) {
  17. unique_instance = new Singleton();
  18. } else {std::cout << "constructor : Unique Singleton already created" << std::endl;}
  19. return unique_instance;
  20. }
  21. void checkSingleton() { std::cout << "checkSingleton" << std::endl;
  22. if (!unique_instance) { std::cout << "checkSingleton : Unique Singleton not created" << std::endl;
  23. } else {
  24. std::cout << "checkSingleton : Unique Singleton already created" << std::endl;
  25. }
  26. }
  27. private:
  28. Singleton() { std::cout << "Unique Singleton Constructor" << std::endl; }
  29. static Singleton* unique_instance;
  30. };
  31. //global variable
  32. Singleton* Singleton::unique_instance = nullptr;
  33. int main(int argc, char* argv[]) {
  34. Singleton *singleton = Singleton::Instance();
  35. singleton->checkSingleton();
  36. //we create a new singleton2 but...
  37. Singleton *singleton2 = Singleton::Instance();
  38. singleton2->checkSingleton();
  39. }