Click to See Complete Forum and Search --> : Singleton class


July 16th, 1999, 08:03 AM
Hi there,

Does any one how can I create a singleton class in VB ?
I wish that every time I create a new object :
dim X as new MyObj
X will reference the same object (this happens inside an activex dll).
Is that possible at all ?


Thanks,
Omer S.

Mikesc
July 17th, 1999, 11:33 AM
I don't know if this answers your question or not but you can do something similar to what you're talking about like this:


Dim a as new Myobj
Dim b as Myobj
a.property=Something
set b=a




This gives you two variables that reference the same object. Is that what you wanted?

Chris Eastwood
July 19th, 1999, 03:17 AM
Hi

Yes - this is possible in VB6 with a little 'Fudging'.

I had to implement a notification object which can be referenced by many different clients. This is used to inform the client when an object we are interested in has changed. I implemented this using an ActiveX DLL -

1. Start a new ActiveX project
2. Add 2 classes, eg

clsSingletonObject - Instancing type - 'Global MultiUse'
clsController - Instancing type 'PublicNotCreatable'

3. Add a module - eg.

CodeModule.Bas

4. In your module, have a public instance of your class, eg.


option Explicit

public gSingleObject as clsSingletonObject




5. In the clsController class, have some code such as :


option Explicit

public Function GetSingleton() as clsSingletonObject

If gSingleObject is nothing then
set gSingleObject = new clsSingletonObject
End If

set GetSingleton = gSingleObject

End Function

private Sub Class_Terminate()

set gSingleton = nothing

End Sub





Your Controller class will now be active in any project that references it - you can still explicitly create an instance of it, eg.


set oController = new clsController




Now, when you want to get the reference to the singleton class (or create the first instance of it):


Dim oController as clsController
Dim oSingleTon as clsSingletonObject

set oController = new clsController
set oSingleTon = oController.GetSingleton

set oController = nothing




Hope you got all that !


Chris Eastwood

CodeGuru - the website for developers
http://www.codeguru.com/vb