Singleton
class Logger {
constructor(options = {}) {
this.level = options.level || 'info';
this.logs = [];
}
log(message) {
this.logs.push(`${this.level}: ${message}`);
console.log(`${this.level}: ${message}`);
}
getLogs() {
return this.logs;
}
}
// Instance holder
let instance;
const LoggerFactory = {
getInstance(options) {
if (instance === undefined) {
instance = new Logger(options);
}
return instance;
},
};
// Get the logger instance with a specific log level
const myLogger = LoggerFactory.getInstance({ level: 'debug' });
// Log some messages
myLogger.log('This is a debug message');
myLogger.log('Another debug message');
// Get the logger instance again (it will be the same instance)
const anotherLogger = LoggerFactory.getInstance();
// This will also log as 'debug' because it's the same instance
anotherLogger.log('Yet another message');
// Get all logs
console.log(anotherLogger.getLogs());PreviousChoosing the Right Design Pattern for Problem-Solving in ProgrammingNextProgramming Languages
Last updated