C++设计模式(1)——单例模式

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

亦称单件模式、Singleton
意图
单例模式是一种创建型设计模式 让你能够保证一个类只有一个实例 并提供一个访问该实例的全局节点。
在这里插入图片描述

问题

单例模式同时解决了两个问题 所以违反了单一职责原则

1、保证一个类只有一个实例。 为什么会有人想要控制一个类所拥有的实例数量 最常见的原因是控制某些共享资源 例如数据库或文件 的访问权限。

它的运作方式是这样的 如果你创建了一个对象 同时过一会儿后你决定再创建一个新对象 此时你会获得之前已创建的对象 而不是一个新对象。

注意 普通构造函数无法实现上述行为 因为构造函数的设计决定了它必须总是返回一个新对象。
在这里插入图片描述

客户端甚至可能没有意识到它们一直都在使用同一个对象。

2、为该实例提供一个全局访问节点。 还记得你 好吧 其实是我自己 用过的那些存储重要对象的全局变量吗 它们在使用上十分方便 但同时也非常不安全 因为任何代码都有可能覆盖掉那些变量的内容 从而引发程序崩溃。

和全局变量一样 单例模式也允许在程序的任何地方访问特定对象。 但是它可以保护该实例不被其他代码覆盖。

还有一点 你不会希望解决同一个问题的代码分散在程序各处的。 因此更好的方式是将其放在同一个类中 特别是当其他代码已经依赖这个类时更应该如此。

如今 单例模式已经变得非常流行 以至于人们会将只解决上文描述中任意一个问题的东西称为单例。

解决方案

所有单例的实现都包含以下两个相同的步骤

1、将默认构造函数设为私有 防止其他对象使用单例类的 new运算符。

2、新建一个静态构建方法作为构造函数。 该函数会 “偷偷” 调用私有构造函数来创建对象 并将其保存在一个静态成员变量中。 此后所有对于该函数的调用都将返回这一缓存对象。

如果你的代码能够访问单例类 那它就能调用单例类的静态方法。 无论何时调用该方法 它总是会返回相同的对象。

真实世界类比

政府是单例模式的一个很好的示例。 一个国家只有一个官方政府。 不管组成政府的每个人的身份是什么 ​ “某政府” 这一称谓总是鉴别那些掌权者的全局访问节点。

单例模式结构

在这里插入图片描述

伪代码

在本例中 数据库连接类即是一个单例。 该类不提供公有构造函数 因此获取该对象的唯一方式是调用 获取实例方法。 该方法将缓存首次生成的对象 并为所有后续调用返回该对象。

// 数据库类会对`getInstance获取实例`方法进行定义以让客户端在程序各处
// 都能访问相同的数据库连接实例。
class Database is
    // 保存单例实例的成员变量必须被声明为静态类型。
    private static field instance: Database

    // 单例的构造函数必须永远是私有类型以防止使用`new`运算符直接调用构
    // 造方法。
    private constructor Database() is
        // 部分初始化代码例如到数据库服务器的实际连接。
        // ……

    // 用于控制对单例实例的访问权限的静态方法。
    public static method getInstance() is
        if (Database.instance == null) then
            acquireThreadLock() and then
                // 确保在该线程等待解锁时其他线程没有初始化该实例。
                if (Database.instance == null) then
                    Database.instance = new Database()
        return Database.instance

    // 最后任何单例都必须定义一些可在其实例上执行的业务逻辑。
    public method query(sql) is
        // 比如应用的所有数据库查询请求都需要通过该方法进行。因此你可以
        // 在这里添加限流或缓冲逻辑。
        // ……

class Application is
    method main() is
        Database foo = Database.getInstance()
        foo.query("SELECT ……")
        // ……
        Database bar = Database.getInstance()
        bar.query("SELECT ……")
        // 变量 `bar``foo` 中将包含同一个对象。

单例模式适合应用场景

如果程序中的某个类对于所有客户端只有一个可用的实例 可以使用单例模式。

单例模式禁止通过除特殊构建方法以外的任何方式来创建自身类的对象。 该方法可以创建一个新对象 但如果该对象已经被创建 则返回已有的对象。

如果你需要更加严格地控制全局变量 可以使用单例模式。

单例模式与全局变量不同 它保证类只存在一个实例。 除了单例类自己以外 无法通过任何方式替换缓存的实例。

请注意 你可以随时调整限制并设定生成单例实例的数量 只需修改 获取实例方法 即 getInstance 中的代码即可实现。

实现方式

在类中添加一个私有静态成员变量用于保存单例实例。

声明一个公有静态构建方法用于获取单例实例。

在静态方法中实现"延迟初始化"。 该方法会在首次被调用时创建一个新对象 并将其存储在静态成员变量中。 此后该方法每次被调用时都返回该实例。

将类的构造函数设为私有。 类的静态方法仍能调用构造函数 但是其他对象不能调用。

检查客户端代码 将对单例的构造函数的调用替换为对其静态构建方法的调用。

单例模式优缺点

在这里插入图片描述

与其他模式的关系

外观模式类通常可以转换为单例模式类 因为在大部分情况下一个外观对象就足够了。

如果你能将对象的所有共享状态简化为一个享元对象 那么享元模式就和单例类似了。 但这两个模式有两个根本性的不同。

1、只会有一个单例实体 但是享元类可以有多个实体 各实体的内在状态也可以不同。
2、单例对象可以是可变的。 享元对象是不可变的。
抽象工厂模式、 生成器模式和原型模式都可以用单例来实现。

C++ 单例模式讲解和代码示例

单例是一种创建型设计模式 让你能够保证一个类只有一个实例 并提供一个访问该实例的全局节点。

单例拥有与全局变量相同的优缺点。 尽管它们非常有用 但却会破坏代码的模块化特性。

在某些其他上下文中 你不能使用依赖于单例的类。 你也将必须使用单例类。 绝大多数情况下 该限制会在创建单元测试时出现。
使用示例 许多开发者将单例模式视为一种反模式。 因此它在 C++ 代码中的使用频率正在逐步减少。
识别方法 单例可以通过返回相同缓存对象的静态构建方法来识别。

基础单例

实现一个粗糙的单例非常简单。 你仅需隐藏构造函数并实现一个静态的构建方法即可。

相同的类在多线程环境中会出错。 多线程可能会同时调用构建方法并获取多个单例类的实例。

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class Singleton
{

    /**
     * The Singleton's constructor should always be private to prevent direct
     * construction calls with the `new` operator.
     */

protected:
    Singleton(const std::string value): value_(value)
    {
    }

    static Singleton* singleton_;

    std::string value_;

public:

    /**
     * Singletons should not be cloneable.
     */
    Singleton(Singleton &other) = delete;
    /**
     * Singletons should not be assignable.
     */
    void operator=(const Singleton &) = delete;
    /**
     * This is the static method that controls the access to the singleton
     * instance. On the first run, it creates a singleton object and places it
     * into the static field. On subsequent runs, it returns the client existing
     * object stored in the static field.
     */

    static Singleton *GetInstance(const std::string& value);
    /**
     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
     */
    void SomeBusinessLogic()
    {
        // ...
    }

    std::string value() const{
        return value_;
    } 
};

Singleton* Singleton::singleton_= nullptr;;

/**
 * Static methods should be defined outside the class.
 */
Singleton *Singleton::GetInstance(const std::string& value)
{
    /**
     * This is a safer way to create an instance. instance = new Singleton is
     * dangeruous in case two instance threads wants to access at the same time
     */
    if(singleton_==nullptr){
        singleton_ = new Singleton(value);
    }
    return singleton_;
}

void ThreadFoo(){
    // Following code emulates slow initialization.
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    Singleton* singleton = Singleton::GetInstance("FOO");
    std::cout << singleton->value() << "\n";
}

void ThreadBar(){
    // Following code emulates slow initialization.
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    Singleton* singleton = Singleton::GetInstance("BAR");
    std::cout << singleton->value() << "\n";
}


int main()
{
    std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
                "If you see different values, then 2 singletons were created (booo!!)\n\n" <<
                "RESULT:\n";   
    std::thread t1(ThreadFoo);
    std::thread t2(ThreadBar);
    t1.join();
    t2.join();

    return 0;
}

线程安全单例

为了解决这个问题 你必须在创建首个单例对象时对线程进行同步。

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class Singleton
{

    /**
     * The Singleton's constructor/destructor should always be private to
     * prevent direct construction/desctruction calls with the `new`/`delete`
     * operator.
     */
private:
    static Singleton * pinstance_;
    static std::mutex mutex_;

protected:
    Singleton(const std::string value): value_(value)
    {
    }
    ~Singleton() {}
    std::string value_;

public:
    /**
     * Singletons should not be cloneable.
     */
    Singleton(Singleton &other) = delete;
    /**
     * Singletons should not be assignable.
     */
    void operator=(const Singleton &) = delete;
    /**
     * This is the static method that controls the access to the singleton
     * instance. On the first run, it creates a singleton object and places it
     * into the static field. On subsequent runs, it returns the client existing
     * object stored in the static field.
     */

    static Singleton *GetInstance(const std::string& value);
    /**
     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
     */
    void SomeBusinessLogic()
    {
        // ...
    }
    
    std::string value() const{
        return value_;
    } 
};

/**
 * Static methods should be defined outside the class.
 */

Singleton* Singleton::pinstance_{nullptr};
std::mutex Singleton::mutex_;

/**
 * The first time we call GetInstance we will lock the storage location
 *      and then we make sure again that the variable is null and then we
 *      set the value. RU:
 */
Singleton *Singleton::GetInstance(const std::string& value)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (pinstance_ == nullptr)
    {
        pinstance_ = new Singleton(value);
    }
    return pinstance_;
}

void ThreadFoo(){
    // Following code emulates slow initialization.
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    Singleton* singleton = Singleton::GetInstance("FOO");
    std::cout << singleton->value() << "\n";
}

void ThreadBar(){
    // Following code emulates slow initialization.
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    Singleton* singleton = Singleton::GetInstance("BAR");
    std::cout << singleton->value() << "\n";
}

int main()
{   
    std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
                "If you see different values, then 2 singletons were created (booo!!)\n\n" <<
                "RESULT:\n";   
    std::thread t1(ThreadFoo);
    std::thread t2(ThreadBar);
    t1.join();
    t2.join();
    
    return 0;
}

来源https://refactoringguru.cn/design-patterns/singleton
仅供学习非商业用途侵删

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: c++