Monday, March 22, 2010

.NET: Singleton Pattern

What is Singleton pattern?

Singleton pattern is a strategy for ensuring that one and only one instance of an object will be created.
In other words a singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.

Implementation of a singleton pattern requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects.

1. The first step is to ensure that every constructor in the class implementing the Singleton pattern is non-public. All constructors must be protected or private.
2. Implement a public/shared method-that creates just one instance of the class.

Example:

Public NotInheritable Class cSinglton
 
Private Shared _CreateInstance As cSinglton = Nothing


Private Sub New()
End

Sub
Public Shared ReadOnly Property CreateInstance() As cSinglton
Get

   If (_CreateInstance Is Nothing) Then

      _CreateInstance = New cSinglton()
   End  If
  Return _CreateInstance
End Get
End Property
End Class

The private shared property _CreateInstance is used to store the reference to the instance of the Singleton class.  Consumer will never able to create a direct instance of the class using "New" keyword because the constructor-Sub New-is defined as private.


Consumer:

Consume should always read the shared property CreateInstance in order to create a new instance of the class which indeed ensures that only one instance of this class will be returned.

Dim clsSinglton As cSinglton
clsSinglton = cSinglton.CreateInstance

Following error message will be display in the event of "Dim clsSinglton As new cSinglton" declaration.
Error: cSinglton.Private Sub New() is not accessible in this context because it is 'Private'.




No comments:

Post a Comment