悉野小楼

导航

C++ 单例模式三种写法

#include <iostream>
#include "Apple.h"

#include "Singleton.h"
#include "ActivityManager.h"
#include "ResourceManager.h"
using namespace MySpace;

int main()
{
    Apple::abc = 10;
    //参考:https://blog.csdn.net/unonoi/article/details/121138176
    // 
    /*
    * 单例模式可以分为 懒汉式 和 饿汉式 ,两者之间的区别在于创建实例的时间不同。

    懒汉式
    系统运行中,实例并不存在,只有当需要使用该实例时,才会去创建并使用实例。这种方式要考虑线程安全。

    饿汉式
    系统一运行,就初始化创建实例,当需要时,直接调用即可。这种方式本身就线程安全,没有多线程的线程安全问题。
    */

    //方法一: 饿汉式单例(本身就线程安全), 在系统启动时就创建好了
    Apple& app = Apple::Instance();
    app.SayHello();
    //用宏方便写
    gApple.SayHello();


    //方法二:
    MySpace::ResourceManager::Instance().SayHello();

    
    //方法三: 使用一个单例宏
    MySpace::Singleton<ActivityManager>::instance().SayHello();
    ACTIVITY_MANAGER.SayHello();
    system("pause");
}

Apple.h

#pragma once
#include <iostream>
class Apple
{
public:
    static Apple& Instance() { return s_kInstance; }
    static int abc;
public:
    inline void SayHello() { std::cout << "Apple Hello" << std::endl; }
private:
    //Apple(); 没写, 这样CPP就不用写了
    //~Apple();

    Apple()
    {
        std::cout << "Apple Constructor" << std::endl;
    }
    static Apple s_kInstance;
};

#define gApple (Apple::Instance())

Apple.cpp

#include "Apple.h"
Apple Apple::s_kInstance;
int Apple::abc = 5;

ResourceManager.h

#pragma once
#include <iostream>

namespace MySpace
{
    class ResourceManager
    {
    public:
        static ResourceManager& Instance();
        void SayHello();
        ResourceManager()
        {
            std::cout << "ResourceManager Constructor" << std::endl;
        }
    };
}

 

ResourceManager.cpp

#include "ResourceManager.h"

using namespace MySpace;

ResourceManager& ResourceManager::Instance()
{
    static ResourceManager resMgr;
    return resMgr;
}
void ResourceManager::SayHello()
{
    std::cout << "ResourceManager Hello" << std::endl;
}

 

Singleton.h

#pragma once

namespace MySpace
{
    template<typename T>
    class Singleton
    {
    public:
        static T& instance()
        {
            static T t;
            return t;
        }

    private:
        Singleton();
        ~Singleton();
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);
    };
}

 

ActivityManager.h

#pragma once
#include <iostream>

namespace MySpace
{
    class ActivityManager
    {
    public:
        void SayHello();
        ActivityManager()
        {
            std::cout << "ActivityManager Constructor" << std::endl;
        }
    };
    #define ACTIVITY_MANAGER MySpace::Singleton<ActivityManager>::instance()
}

 

ActivityManager.cpp

#include "ActivityManager.h"

using namespace MySpace;

void ActivityManager::SayHello()
{
    std::cout << "ActivityManager Hello" << std::endl;
}

 

下载

posted on 2023-07-25 22:04  悉野  阅读(212)  评论(0编辑  收藏  举报