Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 315
sven Avatar asked Jan 13 '09 11:01

sven


People also ask

Why instance is static in Singleton?

It is static so every instance of the Singleton type will use the same variable, hence the "singleton" pattern. Save this answer. Show activity on this post. Succinctly, Singleton is a design pattern used to ensure that only one instance of something is ever created within a given scope.

What are used to initialize instance variables of an object?

A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have the same name as their class and, have no return type. There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

What is a Singleton in programming?

A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object.


1 Answers

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.

like image 100
Janko Mivšek Avatar answered Oct 25 '22 01:10

Janko Mivšek