Singleton Objects using VB.NET
In this article I will explain you about Singleton Objects using VB.NET.
Singleton objects ensure that a class has only one instance and provide a global point of access to it. Some classes must have exactly one and only one instance in a system. A global variable makes an object accessible, but it does not keep you from instantiating multiple new objects. A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance is created by intercepting requests to create new objects, and it can provide a way to access the instance. The Singleton patterns are adequate when there must be exactly one instance of a class and it must be accessible from a well-known access point. They are adequate as well when the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code.
The term singleton is a concept where a global object services all requests. The Singleton concept is a taken from Design Patterns. It is similar to CWinApp in Microsoft Foundation Classes-the one and only application object. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. The Singleton object server is activated only once, and its destructor is never called unless we kill the server object explicitly. Notice that the variable returned by the server is not reset between different invocations of the client. This behavior demonstrates that the server does indeed preserve its state during its lifetime. Let's develop a sample Singleton application. Listing 23.11 shows the remote, singleton object to be created
Listing 23.11: Object Code2 (Listing23.11.vb)
// compile with:
// csc /t:library /out:object2.dll Listing23.11.vb
Namespace ExampleRemoting
Public Class DateTimeServer
Inherits MarshalByRefObject
Private Shared iSayac As Integer = 0
Public Sub New()
Console.WriteLine("DateTime server activated")
End Sub
Protected Overrides Sub Finalize()
Try
Console.WriteLine("DateTime server Object Destroyed...")
Finally
MyBase.Finalize()
End Try
End Sub
Public Function MyMethod(ByVal name As [String]) As [String]
Dim strMessage As [String] = "Hi " & name & ". Here is the current DateTime: " &
DateTime.Now
Console.WriteLine(strMessage)
Return strMessage
End Function
Public Function BeniSay() As Integer
' lock this object to prevent concurrent updates
' to single instance lock(this)
If True Then
Console.WriteLine("Counter: " & System.Threading.Interlocked.Increment(iSayac))
Return iSayac
End If
End Function
End Class
End Namespace
Conclusion
Hope this article would have helped you in understanding Singleton Objects using VB.NET. The next article will explain to you the how we use Singleton Objects with SOAP.