سؤال

I am just writing a sample code to create only 5 objects from a class. I have written my code like this

#include <iostream>

using namespace std;

class SingletonGeneric
{
private:
    static int Count;
    static SingletonGeneric *single;
    SingletonGeneric()
    {
        //private constructor
    }
public:
    static SingletonGeneric* getInstance();
    void method();
    ~SingletonGeneric()
    {
        Count -- ;
    }
};

int SingletonGeneric::Count = 0;
SingletonGeneric* SingletonGeneric::single = NULL;
SingletonGeneric* SingletonGeneric::getInstance()
{
    if( Count >= 0 && Count < 6)
    {
        single = new SingletonGeneric();
        Count = ++;
        return single;
    }
    else
    {
        return single;
    }
}

void SingletonGeneric::method()
{
    cout << "Method of the SingletonGeneric class" << endl;
}
int main()
{
    SingletonGeneric *sc1,*sc2;
    sc1 = SingletonGeneric::getInstance();
    sc1->method();
    sc2 = SingletonGeneric::getInstance();
    sc2->method();

    return 0;
}

but I am not getting the expected result. so please tell me how should I modify my code. Or if there is any other simple way to do it please let me know.

هل كانت مفيدة؟

المحلول

#include <iostream>

using namespace std;

class SingletonGeneric
{
private:
    static int Count;
    static SingletonGeneric *single;
    SingletonGeneric()
    {
        //private constructor
    }
public:
    static SingletonGeneric* getInstance();
    void method();
    ~SingletonGeneric()
    {
        Count -- ;
    }
};

int SingletonGeneric::Count = 0;
SingletonGeneric* SingletonGeneric::single = NULL;
SingletonGeneric* SingletonGeneric::getInstance()
{
    if( Count >= 0 && Count < 5) // should be 5 not 6
    {
        single = new SingletonGeneric();
        Count++;
        return single;
    }
    else
    {
        return NULL;// not the old single
    }
}

void SingletonGeneric::method()
{
    cout << "Method of the SingletonGeneric class" << endl;
}
int main()
{
    SingletonGeneric *sc1,*sc2, *sc3, *sc4, *sc5, *sc6;
    sc1 = SingletonGeneric::getInstance();
    sc1->method();
    sc2 = SingletonGeneric::getInstance();
    sc2->method();
    sc3 = SingletonGeneric::getInstance();
    sc3->method();
    sc4 = SingletonGeneric::getInstance();
    sc4->method();
    sc5 = SingletonGeneric::getInstance();
    sc5->method();
    sc6 = SingletonGeneric::getInstance();
    if (sc6 != NULL) {
        sc5->method();
    } else {
        cout << "only have to create 5 objects" << endl;
    }

    return 0;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top