CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Singleton class

  1. #1
    Guest

    Singleton class

    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.


  2. #2
    Join Date
    Jul 1999
    Posts
    145

    Re: Singleton class

    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?


  3. #3
    Join Date
    May 1999
    Location
    Oxford UK
    Posts
    1,459

    Re: Singleton class

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured