sven
sven

Reputation: 18358

smalltalk singleton pattern: how do I initialize the instance variables?

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?

Upvotes: 11

Views: 5037

Answers (1)

Janko Mivšek
Janko Mivšek

Reputation: 3964

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.

Upvotes: 11

Related Questions