设计模式大全

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

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

 

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

 

一.单例模式

//非线程安全

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 @   言午丶  阅读(105)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示