设计模式(持续更新)

单例模式:

懒汉:

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;
}

工厂模式:

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

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

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

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

后面的慢慢补了。。。

相关推荐
感哥2 小时前
C++ 多重继承
c++
博笙困了2 小时前
C++提高编程 4.0
c++
扑克中的黑桃A3 小时前
[C语言]第三章-数据类型&变量
c++
vker3 小时前
第 1 天:单例模式(Singleton Pattern)—— 创建型模式
java·设计模式
感哥3 小时前
C++ std::string
c++
感哥19 小时前
C++ 面向对象
c++
晨米酱21 小时前
JavaScript 中"对象即函数"设计模式
前端·设计模式
沐怡旸21 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
数据智能老司机1 天前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言