A Global Singleton is a class of which only one instance exists within a program.

Any attempt to use non-static members of the class involves performing operations on this one instance.




 
REM Sacado del forum de FreeBASIC (https://www.freebasic.net/forum/viewtopic.php?t=20432)
 
Type singleton
    Public :
    Declare Static Function crearInstancia() As singleton Ptr
    Declare Destructor ()
    Dim i As Integer
    Private :
    Declare Constructor()
    Declare Constructor(Byref rhs As singleton)
    Declare Static Function instancia(Byval crear As Integer) As singleton Ptr
End Type
 
Static Function singleton.crearInstancia() As singleton Ptr
    Return singleton.instancia(1)
End Function
 
Static Function singleton.instancia(Byval crear As Integer) As singleton Ptr
    Static ref As singleton Ptr = 0
    Function = 0
    If crear = 0 Then
        ref = 0
    Elseif ref = 0 Then
        ref = New singleton
        Function = ref
    End If
End Function
 
Constructor singleton ()
End Constructor
 
Destructor singleton()
singleton.instancia(0)
End Destructor
 
'-----------------------------------------------------------------------------
Dim As singleton Ptr ps1 = singleton.crearinstancia()
ps1->i = 1234
Print ps1, ps1->i
 
Dim As singleton Ptr ps2 = singleton.crearinstancia()
Print ps2
 
Delete ps1
 
Dim As singleton Ptr ps3 = singleton.crearinstancia()
Print ps3, ps3->i
Delete ps3
Sleep
 