C++单例模式

单例模式

懒汉式单例模式的特点是在第一次使用时才创建实例,而饿汉式单例模式在类加载的时候就创建实例。

懒汉式

使用场景:

1、当单例对象的创建和初始化过程比较耗时时,可以使用懒汉式单例模式。因为它可以延迟对象的创建,避免不必要的开销。
2、当单例对象的创建依赖于外部条件,需要在第一次使用时才能确定时,可以使用懒汉式单例模式。

优势:

1、在第一次使用时才创建实例,避免了不必要的内存开销。
2、只有在需要时才创建实例,避免了不必要的初始化和耗时操作。

劣势:

1、在多线程环境下,需要考虑线程安全性,需要使用同步机制来保证只有一个实例被创建。
2、使用同步机制可能会影响性能。

Code

#include <iostream>

class Singleton {
private:
    static Singleton* instance;
    Singleton() {} // private constructor to prevent instantiation

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;

int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();

    if (s1 == s2) {
        std::cout << "s1 and s2 are the same instance" << std::endl;
    } else {
        std::cout << "s1 and s2 are different instances" << std::endl;
    }

    return 0;
}

饿汉式

使用场景:

1、当单例对象的创建和初始化过程比较简单,且在整个程序的生命周期内都会被使用时,可以使用饿汉式单例模式。
2、当单例对象的创建不依赖于外部条件,可以在类加载的时候就确定时,可以使用饿汉式单例模式。

优势:

1、在类加载的时候就创建实例,避免了多线程环境下的同步问题。
2、由于在类加载的时候就创建实例,因此可以保证实例的唯一性。

劣势:

1、在程序启动时就创建实例,可能会造成不必要的内存开销。
2、如果单例对象的创建和初始化过程比较耗时,可能会影响程序启动的性能。

Code

#include <iostream>

class Singleton {
private:
    static Singleton* instance;
    Singleton() {} // private constructor to prevent instantiation

public:
    static Singleton* getInstance() {
        return instance;
    }
};

Singleton* Singleton::instance = new Singleton();

int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();

    if (s1 == s2) {
        std::cout << "s1 and s2 are the same instance" << std::endl;
    } else {
        std::cout << "s1 and s2 are different instances" << std::endl;
    }

    return 0;
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值