Singleton Examples:
We're creating a new web app, and want to make sure that the console log only displays new data when we're in a development build. This is useful for debugging purposes, but we'll want to get rid of them when we deploy the app for real. One way to do this is to create our own logger that uses the Singleton Pattern to be readily available throughout the application!
class Logger
{
// Static instance:
private static instance;
// Instance data:
private loggingEnabled: boolean;
constructor()
{
this.loggingEnabled = true;
}
private static getInstance(): Logger
{
if(!Logger.instance)
{
Logger.instance = new Logger();
}
return Logger.instance;
}
// -------------------------------
// Public-facing static methods:
// -------------------------------
public static enableLogging(state: boolean)
{
let logger = Logger.getInstance();
logger.loggingEnabled = state;
}
public static log(message: any)
{
let logger = Logger.getInstance();
if(logger.loggingEnabled)
{
console.log(message);
}
}
}
Find any bugs in the code? let us know!