ABL - The Problem Solver - .Net FAQ
 

Home
Mission
News
Blog
Tools
FAQ
Publications
Downloads
Contact
Contents

 

Frequently asked questions

.NET FAQ Visual FoxPro FAQ

 


Singleton design pattern

The singleton design is one of the more commonly used design patterns. Normally this requires quite a bit of code in every class. Fortunately generics make this a lot easier and takes out almost all code duplication.

Public Class SingletonDemo
    Public Sub main()
        ' Using the singleton
        TestClass.Instance.Write()
    End Sub
End Class

''' <summary>
''' Generic singleton object wrapper.
'''
</summary>
''' <typeparam name="T"></typeparam>
''' <remarks></remarks>
Public Class SingletonProvider(Of T As New)
    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance() As T
        Get
            Return SingletonCreator.instance
        End Get
    End Property

    Class SingletonCreator
        Shared Sub New()
        End Sub

        Friend Shared ReadOnly instance As New T
    End Class
End Class

''' <summary>
''' Test class for the singleton wrapper.
'''
</summary>
''' <remarks></remarks>
Class TestClass
    Private m_dt As DateTime

    Public Sub New()
        m_dt = DateTime.Now
    End Sub

    ''' <summary>
    ''' Test procedure.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Write()
        Console.WriteLine(m_dt.Ticks.ToString())
    End Sub

    ''' <summary>
    ''' Returning the singleton.
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared ReadOnly Property Instance() As TestClass
        Get
            Return SingletonProvider(Of TestClass).Instance
        End Get
    End Property
End Class


 

Send mail to webmaster@TheProblemSolver.nl with questions or comments about this web site.
Copyright © 1995 - 2007 ABL - The Problem Solver
Last modified: 10/21/06
WF
RSS 2.0