Singleton is a design pattern that makes sure that your application creates only one instance of the class anytime. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.
class SingletonLogger
{
StreamWriter outStream;
int longNumber = 0;
static SingletonLogger _instance;
public static SingletonLogger Instance
{
get { return _instance ?? (_instance = new SingletonLogger()); }
}
SingletonLogger() { }
public void InitializeLogging()
{
if(outStream!=null){
if(outStream!=null){
outStream = new StreamWriter("myLog.txt");
}
}
}
public void ShutDownLogging()
{
outStream.Close();
}
public void LogMessage(string message)
{
outStream.WriteLine((longNumber++) + ";" + message);
}
}
Now to access above Singleton class methods:
SingletonLogger logger=SingletonLogger.Instance;
logger.InitializeLogging();
logger.LogMessage("Hello from sample application.!!");
logger.ShutDownLogging();
logger.ShutDownLogging();
For static classes we do not need to instantiate and we access properties and methods by class name.
public static class Logger
{
static StreamWriter outStream;
static int longNumber = 0;
static public void InitializeLogging()
{
outStream = new StreamWriter("myLog.txt");
}
static public void ShutDownLogging()
{
outStream.Close();
}
static public void LogMessage(string message)
{
outStream.WriteLine((longNumber++) + ";"+message);
}
}
Now to access above static class methods:
Logger.InitializeLogging();
Logger.LogMessage("Hello from sample application.!!");
Logger.ShutDownLogging();
Singleton Class instance can be passed as a parameter to another method whereas static class cannot
class SampleClass
{
public void SingletonMethod(SingletonSampleClass singletonSampleClass)
{
}
}
var SampleClass= new SampleClass();
someClass.SingletonMethod(anotherSingletonSampleClass);
Singleton classes support Interface inheritance whereas a static class cannot implement an interface. So we can reuse our singleton for any number of implementations of interface confirming objects.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
A key point is that static classes do not require an instance reference.
Singleton classes are just user coded classes implementing the Singleton design pattern. Singleton purpose is to restrict instantiation of an class to a single instance.
No comments:
Post a Comment