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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With