I had this interview question: Given a multi threaded system, how should a logger object be designed?
I said it should be static, use singleton design pattern and using a locking mechanism:
public class Logger{
private Logger(){
Console.WriteLine("Logger created");
}
static Logger instance;
static Object key = new Object();
public static Logger getInstance(){
lock (key){
if (instance == null){
instance = new Logger();
}
}
return instance;
}
}
Now I am wondering about the key object initialization - It should be thread safe and it should be initialized once (the same features I need for my logger) - so I developed next solution :
public class Logger{
private Logger(){
Console.WriteLine("Logger created");
}
static Logger instance = new Logger();
public static Logger getInstance(){
return instance;
}
}
Are those solutions basically the same?