Singleton pattern is used where we want to enforce that only one instance of the class is created in our program.
Here is the small example of Singleton class.
public class GlobalServiceManager
{
private GlobalServiceManager()
{
//Initialize your variables here.
}
private static GlobalServiceManager _singleton;//Instance of GlobalServiceManager
public static GlobalServiceManager GetInstance()
{
if ( _singleton == null)
{
_singleton = new GlobalServiceManager();
}
return _singleton;
}
}
Here we have a class GlobalServiceManager and we want to create only one instance of this class. So for that the first thing we did was to make the constructor of class as private so that the instance can not be created from outside of class. Then we created a static variable of type GlobalServiceManager. After that we created a public method "GetInstance" of type GlobalServiceManager. Inside the body of function we are checking if the instance(_singleton) of class is null or not. So when we receive first call for GetInstance, then _singleton will be initialized but then for all sub sequent GetInstance call we will return that instance only.
To get the instance of GlobalServiceManager class from outside of the class, we will simply write:
GlobalServiceManager .GetInstance();
Using this, only one instance of the class will be created.
Hope this will help you understanding the pattern. Happy coding :)
0 Comment(s)