单例设计模式——singleton

来源:互联网 发布:大数据教学视频哪家强 编辑:程序博客网 时间:2024/05/02 15:28
  • 保证在应用程序中,一个类只有一个对象
  • 将构造函数设置为私有,在类的实现中确保生成对象的个数
class Singleton{public:    static Singleton* getInstance(); // 获取句柄    void doSomething();    void destroy();private:    Singleton(); // 私有构造函数    ~Singleton();    Singleton(const Singleton&);    Singleton& operator=(const Singleton&);    static Singleton* instance; // 句柄};
Singleton* Singleton::instance = NULL;void Singleton::doSomething(){    cout << "do something" << endl;}void Singleton::destroy(){    delete this;    instance = NULL;}Singleton::Singleton(){    cout << "singleton created" << endl;}Singleton::~Singleton(){    cout << "singleton destroyed" << endl;}// 非线程安全Singleton* Singleton::getInstance(){    Singleton* ret = instance;    /* 加锁 */    if (instance == NULL){        instance = new Singleton();        ret = instance;    }    /* 加锁 */    return ret;}
int main(){    Singleton* p = Singleton::getInstance();    p->doSomething();    p->destroy();    system("pause");    return 0;}
0 0
原创粉丝点击