设计模式之:单例模式(singleton)

版权声明:copyright@xxdk2017 https://blog.csdn.net/u011583798/article/details/82429545
/*************************************************************************
    > File Name: singleton.cpp
    > Author: XXDK
    > Email: [email protected] 
    > Created Time: Wed 05 Sep 2018 07:13:20 PM CST
 ************************************************************************/

#include<iostream>
using namespace std;

class Object
{
public:
    static Object* obj;

    static Object* GetInstance() {
        if(obj)
            ;
        else 
            obj = new Object();
        return obj;
    }

    void func() {
        std::cout << "this: " << this << std::endl; 
        std::cout<< __func__<< std::endl;
    }

    virtual ~Object(){std::cout<< __func__<< std::endl;}

private:
    Object(){std::cout<< __func__<< std::endl;}
};

Object* Object::obj = NULL;

int main()
{
    Object* po1 = Object::GetInstance();
    po1->func();
    Object* po2 = Object::GetInstance();
    po2->func();

    delete po2;

    po1 = NULL;
    po2 = NULL;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011583798/article/details/82429545
今日推荐