The simplest way to describe singleton class is to look at the definition:

The Singleton Pattern ensures a class has only one instance, and provides a point of access to it.

So why would you need that? Well, there are many objects you only need one of in your application (e.g. Logging, text trimming, for loading strings from a view, etc.). It assures you that you only have one instance of the class and that no one can create another instance on its own. Thus, you need a global access point to deliver the handle to the class.

How do we do that?

I will use my text-trimming class (called CLimitedString) for this presentation.  The class is pretty simple. It’s basic task is to trim text after n characters and append “…” afterwards. Default limit is set to 30, but user can set other value via Limit property.

Private Class CLimitedString
    Private m_nLimit As Integer

    Public Sub New ()
        'setting default value
        Me.m_nLimit = 30
    End Sub

    Public Property Get Limit As Integer
        Limit = Me.m_nLimit
    End Property

    Public Property Set Limit As Integer
        Me.m_nLimit = Limit
    End Property

    Public Function Process (source As String) As String
        If (Len (source) < Me.Limit) Then
            Process = source
            Exit Function
        End If

        Process = Strleftback (Left (source, Me.Limit), " ") &_
    End Function
End Class

As LotusScript does not support private constructors, we will have to create a private class instead. This means that you won’t be able to access this class from anywhere else but this ScriptLibrary. Thus, we need to create a global variable to store class instance and a script library function as a global point of access.

Private currLimitedString As CLimitedString

Script library function:

Function GetLimitedStringInstance As Variant
    If (currLimitedString Is Nothing) Then
        Set currLimitedString = New CLimitedString
    End If

    Set GetLimitedStringInstance = currLimitedString
End Function

As your class is private, this function must return Variant, as code using this class isn’t aware of class’ existence. The usage of the object remains the same.

How do I call my class?

It is quite simple. All you need to do is include your library into an agent for example and then do the following where needed:

Dim vLimitedString As Variant
vLimitedString = GetLimitedStringInstance
vLimitedString.Limit = 10
Messagebox vLimitedString.Process ("My very first singleton class")