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

∥☆過路亽.° 提交于 2020-01-11 04:39:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/438729/smalltalk-singleton-pattern-how-do-i-initialize-the-instance-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!