使用方便的單例類

此處輸入圖片的描述

前言

咱們在軟件開發中會常常用到設計模式,其中運用的最爲普遍的設計模式就是單例,下面是實現單例類的代碼。ios

單例類

#pragma once

template <typename T>
class singleton
{
public:
    singleton() = delete;
    virtual ~singleton() = delete;
    singleton(const singleton&) = delete;
    singleton& operator=(const singleton&) = delete;

    template<typename... Args>
    static T& get_instance(Args&&... args)
    {
        // C++11保證單例的線程安全
        static T t{ std::forward<Args>(args)... };
        return t;
    }
};

#define DEFINE_SINGLETON(class_name) \
public: \
friend class singleton<class_name>; \
using singleton = singleton<class_name>; \
private: \
virtual ~class_name() {} \
class_name(const class_name&) = delete; \
class_name& operator=(const class_name&) = delete; \
public:

使用

#include <iostream>
#include <string>
#include "singleton.h"

class test
{
    // 只須要加入一句代碼,就能夠將test類變爲單例類
    DEFINE_SINGLETON(test);
public:
    test() = default;
    void print()
    {
        std::cout << "Hello world" << std::endl;
    }
};

class test2
{
    // 只須要加入一句代碼,就能夠將test2類變爲單例類
    DEFINE_SINGLETON(test2);
public:
    test2(const std::string& str) : str_(str) {}

    void print()
    {
        std::cout << str_ << std::endl;
    }

private:
    std::string str_;
};

int main()
{
    // 沒有參數的單例
    test::singleton::get_instance().print();
    // 帶有參數的單例
    test2::singleton::get_instance("nihao").print();
    return 0;
}
相關文章
相關標籤/搜索