单子类模型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单子类模型相关的知识,希望对你有一定的参考价值。

Note: This doesn't work in multi-threaded environments, check http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B

Singleton class model
then:
SingletonClass *pSC = SingletonClass::get_singleton_instance();
pSC->any_public_function();
or: SingletonClass::get_singleton_instance()->any_public_function();

at the end of the program don't forget: SingletonClass::destroy();
  1. //.h
  2. class SingletonClass {
  3.  
  4. static SingletonClass *singleton;
  5. SingletonClass();
  6.  
  7. public:
  8. static SingletonClass * get_singleton_instance();
  9. static void destroy();
  10. ~SingletonClass();
  11. };
  12.  
  13.  
  14. //.cpp
  15. SingletonClass *SingletonClass::singleton = NULL;
  16.  
  17. SingletonClass * SingletonClass::get_singleton() {
  18. if( singleton == NULL ) singleton = new SingletonClass();
  19. return singleton;
  20. }
  21.  
  22. void SingletonClass::destroy() {
  23. if( singleton != NULL ) delete singleton;
  24. singleton = NULL;
  25. }
  26.  
  27. SingletonClass::SingletonClass() {
  28. singleton = this;
  29. }
  30.  
  31. SingletonClass::~SingletonClass() {
  32. }

以上是关于单子类模型的主要内容,如果未能解决你的问题,请参考以下文章

Haskell概率单子的类型类问题

Flutter CustomSingleChildLayout 通用单子布局

场景代码题:有200个骑手都想要抢这⼀个外卖单子,如何保证只有一个骑手接到单子?

场景代码题:有200个骑手都想要抢这⼀个外卖单子,如何保证只有一个骑手接到单子?

单子设计模式(Singleton pattern)

类与成员