Skip to content

Instantly share code, notes, and snippets.

@ScottLilly ScottLilly/Logger.cs Secret
Last active Jan 9, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.