• 设计模式-singleton


    定义

    Singleton设计模式是一种责任型模式,它通过隐藏构造器并提供一个对创建对象的单个访问点,确保某个类只有一个实例,并且提供了一个全局访问点。这种模式的宗旨是集中类的职责——创建一个担当独一无二角色的对象(生产唯一实例)。

    实现举例

    用C++(c++11)实现Singleton设计模式的示例代码:

    #include 
    #include 
    
    class Singleton {
    public:
        static Singleton& getInstance() {
            std::call_once(initInstanceFlag, &Singleton::initSingleton);
            return *instance;
        }
    
        void setValue(int value) {
            this->value = value;
        }
    
        int getValue() const {
            return value;
        }
    
    private:
        Singleton() {}
        Singleton(const Singleton&) = delete;
        Singleton& operator=(const Singleton&) = delete;
    
        static void initSingleton() {
            instance = new Singleton();
        }
    
        int value;
        static Singleton* instance;
        static std::once_flag initInstanceFlag;
    };
    
    Singleton* Singleton::instance = nullptr;
    std::once_flag Singleton::initInstanceFlag;
    
    int main() {
        Singleton& singleton1 = Singleton::getInstance();
        Singleton& singleton2 = Singleton::getInstance();
    
        singleton1.setValue(10);
        std::cout << singleton2.getValue() << std::endl; // 输出10
    
        singleton2.setValue(20);
        std::cout << singleton1.getValue() << std::endl; // 输出20
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    代码中使用std::call_once来保证只有一个线程可以初始化单例对象。

    总结

    Singleton设计模式以下特性:

    1. 单例类只能有一个实例。
    2. 单例类必须自己创建自己的唯一实例。
    3. 单例类必须给所有其他对象提供这一实例。

    这种模式的宗旨是集中类的职责——创建一个担当独一无二角色的对象(生产唯一实例)——在类的单个实例中。如果有讲的不对,可以评论留言,一起学习

  • 相关阅读:
    bgp路由更新属性
    python 控制包是否可导入
    Windows系统/Linux系统修改远程连接端口号
    基于BP神经网络算法的性别识别
    kubernetes集群如何更改所有节点IP
    企业应用架构研究系列二:MSF&Scrum 项目管理
    前端笔试练习题——JS7 无重复数组、JS8 数组排序
    Python面向对象特性——多继承【Python中的mro方法搜索顺序、新式类和旧式(经典)类)】
    算法-递归算法
    笔记1.1 计算机网络基本概念
  • 原文地址:https://blog.csdn.net/scy518/article/details/134455809