The use of the singleton pattern is, it creates only one instance. First tme it will create an instance, but when the next call it will return the current instance, not create new instance.
Practical Example:- Normally a user can’t get two credit cards from same bank
public sealed class Logger
{
static Logger instance=null;
static readonly object padlock = new object();
private TextWriterTraceListener listener;
public void Create(string filename)
{
if (listener == null)
{
listener = new TextWriterTraceListener(filename);
}
}
Logger()
{
}
public void WriteLog(string message)
{
listener.Write(message);
}
public static Logger Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Logger();
}
return instance;
}
}
}
}
No comments:
Post a Comment