设计模式(持续更新)

单例模式:

懒汉:

cpp 复制代码
public:
    static Instance& getInstance()
    {
        static instance=new Instance();
        return instance;
    }
前提:Instance(const Instance&)=delete;
Instance(Instance&&)=delete;
Instance& operator=(const Instance&) = delete;

线程安全的懒汉模式

cpp 复制代码
线程安全的:
class Instance{
private:
static Instance* instance;
mutex mut;
public:
static Instance* getInstance();
}
Instance *Instance::instance=nullptr;
Instance::mut;
Instance* Instance::getInstance()
{
    if(instance==nullptr)
    {
        lock_guard<mutex>lock(mut);
        if(instance==nullptr)
        {
            instance=new Instance();
        }
    
    }
    return instance;
}

饿汉模式:

cpp 复制代码
class Instance{
private:
static Instance instance=new Instance();
mutex mut;
public:
static Instance& getInstance();
}
Instance& Instance::getInstance()
{
    return instance;
}

工厂模式:

比较简单但是代码很多,直接放图:

简单工厂:就是创业公司,一个人干多个活

工厂方法:外包,丢给你一个专门的业务

抽象工厂:大厂的核心部门,一个具体工厂干很多核心业务

后面的慢慢补了。。。

相关推荐
见叶之秋10 分钟前
【C++】String类的使用(含模拟实现)
java·开发语言·c++
wuminyu1 小时前
Linux内核线程调度与虚拟线程调度机制系统级深度剖析
java·linux·c语言·jvm·c++
xxwxx__2 小时前
深入理解 C++ 继承:从基础语法到底层原理全解析
c++
键盘会跳舞2 小时前
【C++多线程】多线程性能调优:伪共享、缓存行对齐与吞吐优化
c++·多线程·多线程调优
学习星球3 小时前
编辑距离——二维 DP 的“最小操作“艺术
c++·leetcode·java-consul
OPEN-F3 小时前
ROS2系列教程:tf2坐标变换详解(C++/Python)
开发语言·c++·python
暖焰核心3 小时前
迭代器与模板的结合——stl的list
c++·windows·list
j7~3 小时前
【C++】C++的IO流--详解
c++·c++io流·c++流的概念·stringstream的介绍·c语言的输入与输出
新知图书3 小时前
3.5 智能体设计模式1:反应式智能体与自动导航案例
人工智能·设计模式·智能体
zh_xuan3 小时前
c++ string_view
开发语言·c++