C++ 设计模式之单例模式

发布时间:2024年01月09日

本题目来源自【卡码网KamaCoder

#include <iostream>
#include <string>
//#include <stdlib>
using namespace std;

class ShoppingManager{
    // 成员数据
private:
    // 购物车的单例
   static ShoppingManager *s_shoppingManager;
   
public:
   string goodName;
   int goodNumber;
   // 成员函数
private:
    ShoppingManager(){}
public:
    ~ShoppingManager(){}

public:
    static ShoppingManager * S_GetInstance();
    static void S_KillInstance();
    void PrintInfo()
    {
        std::cout << goodName << " " << goodNumber<< endl;
    }
    
};

ShoppingManager * ShoppingManager::S_GetInstance()
{
    if(ShoppingManager::s_shoppingManager == nullptr)
    {
        ShoppingManager::s_shoppingManager = new ShoppingManager();
        atexit(S_KillInstance);
    }
    return ShoppingManager::s_shoppingManager;
}

void ShoppingManager::S_KillInstance()
{
    if(ShoppingManager::s_shoppingManager != nullptr)
    {
        delete ShoppingManager::s_shoppingManager;
        ShoppingManager::s_shoppingManager = nullptr;
    }
}

// 一定要定义声明的变量
ShoppingManager *ShoppingManager::s_shoppingManager = nullptr;

int main()
{
    ShoppingManager *pointer = ShoppingManager::S_GetInstance();
    while(std::cin >> pointer->goodName >> pointer->goodNumber)
    {
        ShoppingManager::S_GetInstance()->PrintInfo();
    }
    return 0;
}

文章来源:https://blog.csdn.net/K1_uestc/article/details/135422589
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。