(NET) NET (2016)

Singleton in VB.NET

A class of which only a single instance can exist

Return


Ensure a class has only one instance and provide a global point of access to it.







Please download project with this source code from https://github.com/ViacheslavUKR/StandardDisignOopPattern



   1:  ' Singleton Design Pattern.
   2:  ' See description in //www.vb-net.com/ProgramTheory/Singleton.htm
   3:  Class MainApp
   4:      ' Entry point into console application.
   5:      Public Shared Sub Main()
   6:          ' Constructor is protected -- cannot use new
   7:          Dim s1 As Singleton = Singleton.Instance()
   8:          Dim s2 As Singleton = Singleton.Instance()
   9:          ' Test for same instance
  10:          If s1 Is s2 Then
  11:              Console.WriteLine("Objects are the same instance")
  12:          End If
  13:          ' Wait for user
  14:          Console.ReadKey()
  15:      End Sub
  16:  End Class
  17:   
  18:  ' The 'Singleton' class
  19:  Class Singleton
  20:      Private Shared _instance As Singleton
  21:      ' Constructor is 'protected'
  22:      Protected Sub New()
  23:      End Sub
  24:   
  25:      Public Shared Function Instance() As Singleton
  26:          ' Uses lazy initialization.
  27:          ' Note: this is not thread safe.
  28:          If _instance Is Nothing Then
  29:              _instance = New Singleton()
  30:          End If
  31:          Return _instance
  32:      End Function
  33:  End Class




See also:
Creational Patterns Structural Patterns Behavioral Patterns

Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/ProgramTheory/Singleton.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>