设计模式大全

以前写代码自由自在,无拘无束,想怎么写怎么写。

现在有了设计模式的代码,写法都比较多种多样,主要还是为了代码的规范性。设计模型的出现也是因为一个项目之中会有各种各样不同的业务场景,根据业务场景来编写更合适的代码流程。

 

经常用得比较多的是单例模式 策略模式 观察者模式

 

一.单例模式

//非线程安全

class Singleton

{

public:

  static Singleton* getInstance();

  ~Singleton() {}

private:

  Singleton() {}  //构造函数私有

  Singleton(const Singleton& obj) = delete;

  Singleton& operator= (const Singleton& obj) = delete; 

  static Singleton* m_pSingleton;

};

Singleton* Singleton::m_pSingleton = NULL;

Singleton* Singleton::getInstance()

{

  if (m_pSingleton == NULL)

  {

    m_pSingleton = new Singleton;

  }

  return m_pSingleton;

}

 

std::mutex mt;

class Singleton

{

public:

  static Singleton* getInstance();

private:

  Singleton() {}

  Singleton(const Singleton*) = delete;  

  Singleton& operator= (const Singleton&) = delete;

 

  static Singleton* m_pSingleton;

};

Singleton* Singleton::m_pSingleton = NULL;

 

Singleton* Singleton::getInstance()

{

  if (m_pSingleton == NULL)

  {

    mt.lock();

    if (m_pSingleton == NULL)

    {

      m_pSingleton = new Singleton();

    }

    mt.unlock();

  }

  return m_pSingleton;

}

 

posted @ 2020-09-27 15:55  言午丶  阅读(101)  评论(0编辑  收藏  举报