Constructors in Singleton Class

  • Thread starter Thread starter Paul Bromley
  • Start date Start date
P

Paul Bromley

Forgive my ignorance on this one as I am trying to use a Singleton class. I
need to use this to have one instance of my Class running and I think I
understand how to do this. My question however is can a singleton class have
a number of paramterised constructors enabling me to pass in parameters or
not?

I am trying to use the following to send in a parmeter to a constructor, but
getting an error with it. I have a feeling that I am not able to do this. Is
there any other way that I can do this.

Dim sPatName As String = "Green"
Dim EMP As CEmPacc = CEmPacc.Create(sPatName)

Class myApp.CEmPacc cannot be indexed because it has no default property

Many thanks

Paul Bromley
 
As usual, posting a question has made me think about a possible answer. I am
getting around the problem that I had below by accesing a property in my
class and passing in parameters that are then used in my property. I assume
that this is permissible? I know that this is a stupid question, but I also
assume that I can have a number of properties in my singleton class as I
would any other class - I have only seen very basic examples of Singleton
classes.

Thanks

Paul Bromley
 
Paul,

Paul Bromley said:
Forgive my ignorance on this one as I am trying to use a Singleton class.
I
need to use this to have one instance of my Class running and I think I
understand how to do this. My question however is can a singleton class
have
a number of paramterised constructors enabling me to pass in parameters or
not?

Quick and dirty:

\\\
Public Class Singleton
Private m_UserName As String
Private m_Password As String

Private m_DefInstance As Singleton

Private Sub New()
'
End Sub

Private Sub New( _
ByVal UserName As String, _
ByVal Password As String _
)
m_UserName = UserName
m_Password = Password
End Sub

Public Function CreateInstance() As Singleton
If m_DefInstance Is Nothing Then
m_DefInstance = New Singleton
End If
Return m_DefInstance
End Function

Public Function CreateInstance( _
ByVal UserName As String, _
ByVal Password As String _
) As Singleton
If m_DefInstance Is Nothing Then
m_DefInstance = New Singleton(UserName, Password)
End If
Return m_DefInstance
End Function
End Class
///
 
The message you are getting is indicating that you are trying to pass an
argument where one is not expected. What is the "Create" method you have
there?
 
Singletons work just as any other class with the exception that you can't
inherit from them.
 
Many thanks Herfried, Scott & Mike,

I see exactly where I am going wrong now especially from the example that
Herfried has given - I was foolishly trying to send parameters to a Private
Sub New(), and I see quite obviously now that I need to send these to a
Public Function CreateInstance() As Singleton instead. I had not seen any
examples of using this type of class with parameters. Another stupid
question - I assume that I can place other initialisation code in this
function - i.e. calls to other Sub routines etc?

Again many thanks - as always I have learnt a lot - will try this later -
off to work now.

Best wishes

Paul Bromley
 
Paul,

Paul Bromley said:
I see exactly where I am going wrong now especially from the example that
Herfried has given - I was foolishly trying to send parameters to a
Private
Sub New(), and I see quite obviously now that I need to send these to a
Public Function CreateInstance() As Singleton instead. I had not seen any
examples of using this type of class with parameters. Another stupid
question - I assume that I can place other initialisation code in this
function - i.e. calls to other Sub routines etc?

Yes, you can do that.
 
Parameters in a Singleton depend entirely on the purpose of the
parameters. It may mean a singleton that needs initialization or you
could be talking about a different pattern--Flyweight.

If the parameters are intended to initialize the singleton and should
only be provided once, or should match if provided a second time, and
the singleton will still be a true singleton in that there will always
only be a single object whose reference won't be changed, then two
Instance properties should be implemented. One has no params and
returns the existing object only ifit has already been initialized
(throw error otherwise). The second accepts the params and if it's
the first call it initializes and returns the singleton. If it's a
subsequent call it should verify that the parameters match. See
ParameterizedSingleton below.

If the parameters are intended to represent a unique object where
there can be multiple instances of the object based on parameters but
all instances for the same parameters should be identical then the
object is not a Singleton but a Flyweight. In this case the shared
property is a collection of objects and not a single instance and is
indexed by one or both of the parameters. See Flyweight below.

HTH,

Sam


Public NotInheritable Class ParameterizedSingleton

Private _username As String
Private _password As String

Private Shared _instance As ParameterizedSingleton

Private Sub New(ByVal username As String, ByVal password As String)
_username = username
_password = password
End Sub

' Singleton getters. Use Instance(username,password) first
' time to initialize the singleton and use Instance() on
' subsequent calls to use the existing singleton.

Public Shared ReadOnly Property Instance() As
ParameterizedSingleton
Get
If _instance Is Nothing Then
Throw New Exception("ParemeterizedSingleton has not been
properly initialized.")
End If

Return _instance
End Get
End Property

Public Shared ReadOnly Property Instance(ByVal username As String,
ByVal password As String) As ParameterizedSingleton
Get

If _instance Is Nothing Then
_instance = New ParameterizedSingleton(username, password)
Else
If Not _instance.UserName = username OrElse _
Not _instance.Password = password Then

Throw New Exception("ParemeterizedSingleton has already
been initialized.")
End If
End If

Return _instance
End Get
End Property

Public ReadOnly Property UserName() As String
Get
Return _username
End Get
End Property

Public ReadOnly Property Password() As String
Get
Return _password
End Get
End Property

End Class


Public NotInheritable Class Flyweight

Private _username As String
Private _password As String

Private Shared _instances As New Hashtable

Private Sub New(ByVal username As String, ByVal password As String)
_username = username
_password = password
End Sub

Public Shared ReadOnly Property Instance(ByVal username As String,
ByVal password As String) As Flyweight
Get

Dim obj As Flyweight

If _instances.Contains(username) Then
obj = DirectCast(_instances(username), Flyweight)
If obj.Password <> password Then
Throw New Exception("User '" + username + "' is already
initialized.")
End If
Else
obj = New Flyweight(username, password)
_instances(username) = obj
End If

Return obj
End Get
End Property

Public Shared ReadOnly Property Instance(ByVal username As String)
As Flyweight
Get
If Not _instances.Contains(username) Then
Throw New Exception("User '" + username + "' not
initialized.")
End If

Return DirectCast(_instances(username), Flyweight)
End Get
End Property
Public ReadOnly Property UserName() As String
Get
Return _username
End Get
End Property

Public ReadOnly Property Password() As String
Get
Return _password
End Get
End Property

End Class



Forgive my ignorance on this one as I am trying to use a Singleton class. I
need to use this to have one instance of my Class running and I think I
understand how to do this. My question however is can a singleton class have
a number of paramterised constructors enabling me to pass in parameters or
not?

I am trying to use the following to send in a parmeter to a constructor, but
getting an error with it. I have a feeling that I am not able to do this. Is
there any other way that I can do this.

Dim sPatName As String = "Green"
Dim EMP As CEmPacc = CEmPacc.Create(sPatName)

Class myApp.CEmPacc cannot be indexed because it has no default property

Many thanks

Paul Bromley

B-Line is now hiring one Washington D.C. area VB.NET
developer for WinForms + WebServices position.
Seaking mid to senior level developer. For
information or to apply e-mail resume to
sam_blinex_com.
 
Thanks Herfired, excellent example of a singleton class..I've added this to
my colleciton of code snippets.
 
Dennis,

Dennis said:
excellent example of a singleton class..I've added this to
my colleciton of code snippets.

Well, that's only the "very basic" sample. Some more information and
samples on the Singleton design pattern:

Implementing the Singleton Pattern in C#
<URL:http://www.yoda.arachsys.com/csharp/singleton.html>

Exploring the Singleton Design Pattern
<URL:http://msdn.microsoft.com/library/en-us/dnbda/html/singletondespatt.asp>

Design Pattern: Singleton in C#
<URL:http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=486>

Design Patterns: Singleton
<URL:http://www.dofactory.com/Patterns/PatternSingleton.aspx>
 
Thanks all for your help on this one, especially Sam & Herfried for the
comprehensive code samples.

Best wishes


Paul Bromley
 
Samuel,

Many thanks for this answer. It seems that I cannot use a singleton with
parameters for what I wanted as I will not have one instance. I think my
best way around it is to access the properties using parmeters.

Best wishes

Paul Bromley
 
Back
Top