I have example code on C++ that describes my solution:
#include <iostream>
class Singleton {
private:
static Singleton* instance;
Singleton() {
std::cout << "Instance created" << std::endl;
}
Singleton(const Singleton&);
Singleton& operator=(Singleton&);
public:
static Singleton* getInstance();
static void m1();
void m2();
};
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
void Singleton::m1() {
std::cout << "Called m1" << std::endl;
instance->m2();
}
void Singleton::m2() {
std::cout << "Called m2" << std::endl;
}
int main() {
Singleton* singleton = Singleton::getInstance();
Singleton::m1();
return 1;
}
Is it correct that I call instance
method m2
from static method m1
?
Doesn't this cause any problems in maintaining and understanding the code, or would it be better to make m2
method also static?