Example :-
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation
Implementation of Singleton pattern :-
///
/// Thread-safe singleton example without using locks
///
public sealed class SingletonClass
{
private static readonly SingletonClass singletonInstance = new SingletonClass();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonClass()
{
}
private SingletonClass()
{
}
///
/// The public Instance property to use
///
public static SingletonClass SingletonInstance
{
get { return singletonInstance ; }
}
}
Happy to code...
Hiii...One more example to clear singleton approach :-
I have implement progress bar for ma current application so i am giving some reference here:-
#region Private Fields
private static StatusProgressBar _instance = null;
#endregion
#region Constructor
private StatusProgressBar()
{
this.Style = ProgressBarStyle.Blocks;
this.Step = 1;
}
#endregion
#region Properties
///
/// Get Singleton instance of progressBar
///
public static StatusProgressBar Instance
{
get
{
if (_instance == null)
{
_instance = new StatusProgressBar();
}
return _instance;
}
}
#endregion
Made the above class as public and access it suppose class name is StatusProgressBar
StatusProgressBar.Instance.PerformStep();
then if instance is already running then it will return that instance otherwise will return a new instance.
Very good post thanks to post this....I m a regular visitor of your blog keep posting....
ReplyDeleteSaurabh I have a question in my mind;
ReplyDelete1.Can you please Explain the Code and explain how is it restricting the cloning of the object. As per my knowledge If object of this class Can be cloned then it will not be Singleton class .
2. Why do we need a Singleton class ? tell me any situation where use of singleton class is indispensible.
Thanks in Advance
Rajesh Kumar
Hi rajesh...
ReplyDelete1 :- In real world if you are asking where you need singleton class then i have a instance in ma mind i had a class in which there was 10 + event calling was handled and first time when a object made then it call and handle all those events but again when i need to use a method of this class in some other solution then i need to create object(i couldn't make static) there but if there is already a object running then there was no need to create a new instance that can give me performance hit due to 10+ event calling so i use theat instance using singleton pattern .Thats the real example which i faced.
2:- In the above code when you already create a object first time then if there is need to access some method,property in some other class and object is already running then call the property which gives you instance that will restrict the cloning of object.
Saurabh singh :-
ReplyDeleteThis will make your problem more clear
Ensure a class has only one instance, and provide a global point of access to it.