Constructor

mudhunny

Newcomer
Joined
Jul 24, 2003
Messages
3
Hi ... anyone knows whether can i initialize a public class using a private constructor ? can it be done ?
 
Visual Basic:
Public Class DSOUserContextBR

#Region "Member Variables"

    private shared myInstance As DSOUserContextBR

    Private m_Anmeldename As String
    Private m_Workstation As String
#End Region

#Region "Properties"


    Public ReadOnly Property User() As String
        Get
            Return m_Anmeldename
        End Get
    End Property

    Public ReadOnly Property Workstation() As String
        Get
            Return m_Workstation
        End Get
    End Property

#End Region

#Region "Public Methods"
    Public Shared Function GetInstance() As DSOUserContextBR
        If myInstance Is Nothing Then
            myInstance = New DSOUserContextBR()
        End If
        Return myInstance
    End Function

    Public Sub Initialize()
     'So stuff with member variables
    End Sub

#End Region

#Region "Private Methods"
    Private Sub New()
        'Dadurch, dass New() Private ist, kann niemand von ausserhalb 
        'ein neues Objekt erzeugen. Ha! 
        'Es muss also die öffentliche "getInstance" Methode verwendet werden, 
        'die auf die bestehende Instanz zeigt --> Singleton ! Voila!
        m_Anmeldename = Environment.UserName        'Anmeldename
        m_Workstation = Environment.UserDomainName  'Rechner

    End Sub

#End Region

Not exactly what you need but I hope you get the idea.
 
that sure gives me some idea. thanks a lot. i have another question. what if i want to do something like the datarow and datatable relationship where you can only get a new instance of datarow through datatable. any idea ?
 
You can do something along the lines of:

Visual Basic:
Public Class TestParent
    Public Function AddChild() As TestChild
         '-Factory method that returns a TestChild instance...
         Return New TestChild()
    End Function
End Class

Public Class TestChild
    Friend Sub New()
    '-Declare constructor as Friend so as not to be directly creatable outside this assembly.
    End Sub
End Class

If you compile this to a Class Library project and use the dll in another app, an instance of TestChild can be declared but can't be created directly. All instances of TestChild can only come from the AddChild method of a TestParent instance.
 
This trick with a private constructor is used to ensure that only 1 instance of the class can be made in memory, no?
 
Back
Top