单例类与静态方法 [英] Singleton class with Static Method

查看:77
本文介绍了单例类与静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,





在Singleton课程中我们为什么需要静态方法?



请找到以下示例:



Hi All,


In Singleton class why we need static method?

Please find the below example:

#include<iostream>

using namespace std;

class Singleton
{
private:
    static bool instanceFlag;
    static Singleton *single;
    Singleton()
    {
        //private constructor
    }
public:
    static Singleton* getInstance();
    void method();
    ~Singleton()
    {
        instanceFlag = false;
    }
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
    if(! instanceFlag)
    {
        single = new Singleton();
        instanceFlag = true;
        return single;
    }
    else
    {
        return single;
    }
}

void Singleton::method()
{
    cout << "Method of the singleton class" << endl;
}

int main()
{
    Singleton *sc1,*sc2;
    sc1 = Singleton::getInstance();
    sc1->method();
    sc2 = Singleton::getInstance();
    sc2->method();

    return 0;
}





问候,

Ranjith



Regards,
Ranjith

推荐答案

如果getInstance()不是静态的,你只能为该类的对象调用它。但是当你称它时,你通常没有那个阶级的对象;相反,你想要检索它或创建唯一的对象。因此该方法必须是静态的。



顺便说一下, instanceFlag 是多余的。你可以同样测试单个指针不等于NULL。
If the getInstance() were not static you could only call it for an object of the class. But at the time you call it you typically have no object of that class; instead you want to either retrieve it or create the one and only object. And hence the method must be static.

And, by the way, the instanceFlag is superfluous. You could equally well test the single pointer on being not equal to NULL.


这篇关于单例类与静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆