2016-12-13 3 views
1

Я новичок в программировании, и я пытался использовать программу, которая делает класс singleton. Это правильный подход для создания класса singleton ??Является ли это правильной программой создания класса singleton?

#include <iostream> 
using namespace std; 
class Singleton 
{ 
private: 
    static bool instanceFlag; 
    static Singleton *single; 
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"; 
} 
int main() 
{ 
    Singleton *sc1,*sc2; 
    sc1 = Singleton::getInstance(); 
    sc1->method(); 
    sc2=Singleton::getInstance(); 
    sc2->method(); 
    return 0; 
} 

Это правильный способ сделать класс singleton ??

+0

есть много примеров: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern?rq=1 – EdChum

+0

related/dupe: http://stackoverflow.com/questions/1008019/c -singleton-design-pattern – NathanOliver

+0

Прежде всего, конструктор должен быть закрытым, иначе вы не заставляете пользователей называть 'getInstance' – EdChum

ответ

1

попробовать это решение:

class Singleton { 
private: 
    static Singleton* instance; 
    Singleton() {} // must be private 
public: 
    static Singleton* getInstance() { 
     if (instance == NULL) 
      instance = new Singleton(); 
     return instance; 
    } 
    void method() { cout << "Method of the singleton class\n"; } 
}; 
Singleton* Singleton::instance = NULL; 
3

Вы чрезмерно усложнять. Попробуйте Scott Meyers синглтон:

struct SingletonClass { 
    // instance() function return a reference 
    static SingletonClass& instance() { 
     // static local variable are initialized one time. 
     static SingletonClass inst; 

     // We return the instance, which is the same for every calls. 
     return inst; 
    } 

private: 
    // Private since we don't want other class to create instances 
    SingletonClass() = default; 

    // Our class is not copiable or movable 
    SingletonClass(const SingletonClass&) = delete; 
    SingletonClass(SingletonClass&&) = delete; 
    SingletonClass& operator=(const SingletonClass&) = delete; 
    SingletonClass& operator=(SingletonClass&&) = delete; 
}; 

Вы можете использовать свой класс так:

auto& myInstance = SingletonClass::instance(); 

Бонус: Он не использует динамическое распределение, это поточно, и гораздо проще.

Смежные вопросы