How can I shorten a singleton call?
I have a singleton class that basically deals with logs. Every place at which I call it in the code, I have to type:
LogClass::开发者_Go百科GetInstance()->WriteToLog("text");
How can I shorten this call so that I can just type WriteToLog("text")
and it will call the function on the singleton object?
Use a forwarding function
inline void WriteToLog(...string...)
{ LogClass::GetInstance()->WriteToLog(.....string......); }
Add a static function to LogClass:
class LogClass {
static void Write( const std::string & s ) {
GetInstannce()->WriteToLog( s );
}
};
then:
LogClass::Write( "foobar" );
#define LOG(str) LogClass::GetInstance()->WriteToLog(str);
You can a pointer to temporarily store an alias of the class locally in your function: (Assuming "GetInstance returns a pointer to the singleton)
void foo()
{
Singleton* logger = LogClass::GetInstance();
logger->WriteToLog(...string...);
logger->WriteToLog(...string...);
}
I like to use a reference and an operator() overload.
In LogClass.h file
class LogClass
{
public:
static LogClass& GetInstance()
{
static LogClass singleton;
return singleton;
}
void operator()( std::string msg );
//...
};
extern LogClass& myDebug;
In LogClass.cpp file
LogClass& myDebug = LogClass::GetInstance();
void LogClass::operator()( std::string msg )
{
// my stuff to to with the msg...
}
//...
Then, I can use it this way (in any file LogClass.h is included):
myDebug("text");
Indeed, you must keep in mind that it's a global variable... but on another side the GetInstance method is called once.
Next I do like to add an easy switch to deactivate all debugMsg at once...
so I add the following:
#if DEBUG_MODE
#define MY_DEBUG( msg ) myDebug( msg )
#else
#define MY_DEBUG( msg ) // will replace the myDebug calls by nothing.
#endif
Thus, I can use:
MY_DEBUG("text"); // instead of myDebug("text");
So I can easily turn off all the debug messages at once.
Personally, I find it bad practice to expose the "Singleton".
I used to have static
functions over a static
state:
class Logger {
public:
static void Write(std::string const& s);
private:
static std::ifstream _file;
};
However, I much prefer using Monoids now. They are just Singletons in disguise, of course, but it's much easier to migrate away from singleton-ness afterwards.
class Logger {
public:
void Write(std::string const& s);
private:
static std::ifstream _file;
};
You still have to handle all the Singletons issues, but you can migrate away from it with more ease.
精彩评论