【设计模式-C++】单例模式

Singleton.h

#pragma once

#include <utility>

template <typename T>
class Singleton {
    
    
public:
    template<typename... Args>
    static T* Instance(Args&&... args) {
    
    
        if (instance_ == nullptr) {
    
    
            instance_ = new T(std::forward<Args>(args)...);
        }
        return instance_;
    }

    static void destroyInstance() {
    
    
        delete instance_;
        instance_ = nullptr;
    }

private:
    static T* instance_;
};

template <class T> T* Singleton<T>::instance_ = nullptr;

example:

#include "Singleton.h"

#include <iostream>

class A{
    
    
public:
    A(){
    
    };
    void func() {
    
    
        std::cout << "hello" << std::endl;
    };
};

int main() {
    
    
    Singleton<A>::Instance()->func();
    return 0;
}

console:

hello

猜你喜欢

转载自blog.csdn.net/tech2ipo/article/details/90050785