views:

825

answers:

1

I'm having trouble in getting the singleton pattern to initialize a instance variable in smalltalk. (here is a link to another implementation for clarification)

this is what I have:

new

^UniqueInstance ifNil: [UniqueInstance := self basicNew.
                  UniqueInstance: instanceVar := Object new. ].

that last line (UniqueInstance: instanceVar := Object new.) doesn't work, but that's basically what I need to do: instantiate instanceVar as an Object before returning UniqueInstance back to the caller.

Notice that this 'new' method is used as a classinstantiation, and that libraries is a instance variable of UniqueIsntance (the isntance of the wanted class).

Can anyone point me in the right direction?

+6  A: 

Try simpler:

YourClass class>>singleton

       UniqueInstance ifNil: [UniqueInstance := self basicNew initialize].
       ^UniqueInstance

then on instance side of your class implement an appropriate #initialize method, for example:

YourClass>>initialize

          someInstvar := someInitalValue.
         ^self

Update:: Name of the class method accessing the singleton varies, it can be #default, #current, or #singleton. I mostly use later.

Janko Mivšek
thanks, that did the trick!
Sven
You are welcome. Happy Smalltalking!
Janko Mivšek
you might want to also add "super initialize." depending on your house rules about initialization...
Randal Schwartz
Another syntax trick that I often use is possible because #ifNil: returns the receiver if it's not nil. So you can do the whole method in one line: "^UniqueInstance ifNil: [UniqueInstance := self basicNew initialize]"
Ash Wilson