懒汉模式

  1. class Singleton{
  2. public:
  3. static Singleton& getInstance(){
  4. if(m_pIntance == nullptr){
  5. m_mutex.lock(); // 互斥锁,保证多线程中也是单例的。
  6. if(m_pIntance == nullptr){
  7. m_pIntance = new Singleton();
  8. }
  9. m_mutex.unlock();
  10. }
  11. return m_pInstance;
  12. }
  13. void fuck(){
  14. cout << "fuck something" << endl;
  15. }
  16. private:
  17. Singleton *m_pIntance;
  18. std::mutex m_mutex;
  19. Singleton() = delete; //阻止外部构造
  20. Singleton(Singleton const &singleton) = delete; //阻止拷贝构造
  21. Singleton& operator=(Singleton const &singleton) = delete; //阻止拷贝赋值
  22. };
  23. main()
  24. {
  25. Singleton::getInstance().fuck();
  26. }

饿汉模式

  1. class Singleton{
  2. public:
  3. static Singleton& getInstance(){
  4. static Singleton instance; //在程序启动时就加载,线程安全。
  5. return instance;
  6. }
  7. void fuck(){
  8. cout << "fuck something" << endl;
  9. }
  10. private:
  11. Singleton() = delete; //阻止外部构造
  12. Singleton(Singleton const &singleton) = delete; //阻止拷贝构造
  13. Singleton& operator=(Singleton const &singleton) = delete; //阻止拷贝赋值
  14. };
  15. main()
  16. {
  17. Singleton::getInstance().fuck();
  18. }