hide the constructor

seco

Well-known member
Joined
Mar 4, 2007
Messages
66
Programming Experience
Beginner
Hi

in OOP design i can make the constructor private in order not to instantiate object from the class . and so i can make function that return the object

why we make the constructor private? what we gain from this?

thanks in advance.
 
You mean something like this:

VB.NET:
Public Class Singleton
    Private Sub New()
 
    End Sub
 
    Public Shared Instance As New Singleton
 
    Public Sub DoSomething()
 
    End Sub
End Class
 
Public Sub Main
    Singleton.Instance.DoSomething()
End Sub

The point is that the singleton class can only be instantiated once during an application run. And so you can't accidentally instantiate a second object (via calling New). This is discussed in various design patterns books, the pattern is called "Singleton".
 
Of course, the following can also be used to achieve the same effect:

VB.NET:
Public Shared Class Singleton
 
    Public Sub DoSomething()
 
    End Sub
End Class
 
Public Sub Main
    Singleton.DoSomething()
End Sub

The main thing with singleton in IfYouSaySo's style is that you can defer instantiation (IfYouSaySo's example does not show this) to the first time it is used. I'm not sure whether .NET lazily instatiates things like this anyway (i.e. no instantiate even of statics, until first use) ?
 
Back
Top