Skip to content

Instantly share code, notes, and snippets.

@ScottLilly
Last active January 9, 2016 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottLilly/fa590a163ae22ab141f3 to your computer and use it in GitHub Desktop.
Save ScottLilly/fa590a163ae22ab141f3 to your computer and use it in GitHub Desktop.
Implementing a Singleton, with a static function
namespace Workbench
{
public class Logger
{
// Notice that this variable is static.
// It must be static, because it is a class-level variable that a static function wants to use.
// The function can be called without instantiating a Logger class,
// so any class-level variables that it uses must also be static.
private static Logger _logger;
// The constructor is private, so it can only be called by other functions in this class.
// This is how we prevent other classes from creating a new Logger object.
private Logger()
{
// Pretend we have a lot of setup code in here, connecting to a database, or something
}
// Whenever another class wants to use the Logger, they call this function.
// If there is no existing _logger object, it creates a new one.
// Then, it returns the one _logger object.
public static Logger GetLogger()
{
if(_logger == null)
{
_logger = new Logger();
}
return _logger;
}
public void WriteToLog(string message)
{
// Code to write to your logging database or file
}
}
}
namespace Workbench
{
public class RegularClass
{
public RegularClass()
{
// Get the shared/singleton logger object
Logger myLogger = Logger.GetLogger();
myLogger.WriteToLog("Got to this place in the code");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment