-
-
Save ScottLilly/fa590a163ae22ab141f3 to your computer and use it in GitHub Desktop.
Implementing a Singleton, with a static function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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