Jump to content

  • Log In with Google      Sign In   
  • Create Account

#Actualmetsfan

Posted 18 June 2012 - 07:10 PM


You can do something like this

class Log {
public:
static Log* Get() {
	 if( !m_pInstance )
		  m_pInstance = this;
	  return m_pInstance;
}
protected:
	 Log* m_pInstance;
};

Then use the log like this within your classes
Log* pLog = Log::Get();
pLog->Write( "Me and the Cap't make it happen!" );



This is the "singleton pattern" or as I like to refer to it "the greatest sin perpetuated by programmers with good intentions."

The singleton thing has been debated to death, so if you're interested, I invite you to go search around for any of the dozens of threads on the subject. For now, though, I will leave it at this: please, don't use that code. Ever.


Singletons used incorrectly are a bad idea, but Singletons do have their place. There are times when having two instances of a class is an error and may/will cause your program to malfunction. I am well aware of the downsides (increased strong coupling, problems with unit testing, debugging headaches), but there are times when having just one instance of a class is needed. I will say though, that a logger class is not one of those cases, having two logger classes shouldn't break your application. There are situations though where a singleton pattern makes sense, and not only can be used, but should.

However, it goes without saying that code is crap =) I don't think the poster was intending to provide copy/paste code (at least I hope not!)

#1metsfan

Posted 18 June 2012 - 07:09 PM


You can do something like this

class Log {
public:
static Log* Get() {
	 if( !m_pInstance )
		  m_pInstance = this;
	  return m_pInstance;
}
protected:
	 Log* m_pInstance;
};

Then use the log like this within your classes
Log* pLog = Log::Get();
pLog->Write( "Me and the Cap't make it happen!" );



This is the "singleton pattern" or as I like to refer to it "the greatest sin perpetuated by programmers with good intentions."

The singleton thing has been debated to death, so if you're interested, I invite you to go search around for any of the dozens of threads on the subject. For now, though, I will leave it at this: please, don't use that code. Ever.


Singletons used incorrectly are a bad idea, but Singletons do have their place. There are times when having two instances of a class will cause your program to malfunction. I am well aware of the downsides (increased strong coupling, problems with unit testing, debugging headaches), but there are times when having just one instance of a class is needed. I will say though, that a logger class is not one of those cases, having two logger classes shouldn't break your application. There are situations though where a singleton pattern makes sense, and not only can be used, but should.

However, it goes without saying that code is crap =) I don't think the poster was intending to provide copy/paste code (at least I hope not!)

PARTNERS