smalltalk单例模式:如何初始化实例变量? [英] smalltalk singleton pattern: how do I initialize the instance variables?
问题描述
我在获取单例模式以在smalltalk中初始化实例变量时遇到麻烦. (这是链接到另一个实现进行澄清)
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)
这就是我所拥有的:
new
^UniqueInstance ifNil: [UniqueInstance := self basicNew.
UniqueInstance: instanceVar := Object new. ].
最后一行(UniqueInstance:instanceVar:= Object new.)不起作用,但这基本上是我需要做的:将instanceVar实例化为Object,然后将UniqueInstance返回给调用者.
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.
请注意,此新"方法用作类实例,并且库是UniqueIsntance(所需类的实例)的实例变量.
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?
推荐答案
尝试更简单:
YourClass class>>singleton
UniqueInstance ifNil: [UniqueInstance := self basicNew initialize].
^UniqueInstance
然后在类的实例端实现适当的#initialize方法,例如:
then on instance side of your class implement an appropriate #initialize method, for example:
YourClass>>initialize
someInstvar := someInitalValue.
^self
更新:访问单例的类方法的名称各不相同,可以是#default,#current或#singleton.我以后主要使用.
Update:: Name of the class method accessing the singleton varies, it can be #default, #current, or #singleton. I mostly use later.
这篇关于smalltalk单例模式:如何初始化实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!