Whenever we want that a class has only one instance and it should have global point to access it but allowing the flexibility to create more objects if the situation changes in that case we will use Singleton Design Pattern.Singleton design Pattern falls in the category of Creational Design Pattern.Though the reason seems to be quite easy when to use Singleton design Pattern, the difficulty lies in choosing the class that we want to behave as Singleton. More on this I will explain in my next article.But there might be few situations when we are forced to implement Singleton Design Pattern. One of those situations can be related to Licensing agreement where we are allowed to have only one connection per License agreement. In these type of scenarios, if multiple instances are created then Exception related to License agreement can be thrown. I have faced this while implementing a Pop3 client. In this case, the class where Pop3 client object is initialized must implement Singleton Design Pattern. As of now I will just concentrate on how to implement Singleton Design Pattern once we have decided on the class to have above kind of property. Implementation of Singleton Design Pattern :- Singleton Design Pattern can be implemented in two ways :- 1. Field Initialization :-In the first approach we have initialized the _testsingleton in the field declaration only. Though from the code perspective this is perfectly legal that is no compilation error is generated, it has certain drawbacks which are listed as follows:-
namespace Test
{
public class TestSingleton
private static TestSingleton _testsingleton = new TestSinleton(); // Field Intialization
// Constructor is private here to to prevent instantiation by outside
private TestSingleton()
// construct object . . .
}
//A Public Method is exposed to the ouside world to get an instance only if no
// of this class is created
public static TestSingleton GetInstance()
if (_testsingleton == null)
_testsingleton = new TestSingleton();
return _testsingleton;
using System;
private static TestSingleton _testsingleton; // Only Field Declaration
private static Object _testLock = typeof(TestSingleton); //This is needed in Multithreaded
// Environment
// Initializtion is done only in this method
lock (_testlock) // Give Lock to a Particular Thread.Till this Lock is not acquired by
// Second thread, it can intantiate the singleton object.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: