【问题标题】:Difference between new and initialize in Smalltalk?Smalltalk中new和initialize的区别?
【发布时间】:2011-04-17 09:58:16
【问题描述】:

一个新手问题,new和initialize有什么区别?

【问题讨论】:

    标签: smalltalk


    【解决方案1】:

    没错。当您发送消息#new 时,它不仅会创建对象,还会发送消息#initialize。这使您可以自定义对象的初始化。看:

    Behavior >> new
    "Answer a new initialized instance of the receiver (which is a class) with no indexable variables. Fail if the class is indexable."
    
    ^ self basicNew initialize
    

    然后:

     ProtoObject >> initialize
    "Subclasses should redefine this method to perform initializations on instance creation" 
    

    还有:

       Behaviour >> basicNew
    "Primitive. Answer an instance of the receiver (which is a class) with no 
    indexable variables. Fail if the class is indexable. Essential. See Object 
    documentation whatIsAPrimitive."
    
    <primitive: 70>
    self isVariable ifTrue: [ ^ self basicNew: 0 ].
    "space must be low"
    OutOfMemory signal.
    ^ self basicNew  "retry if user proceeds"
    

    所以...#basicNew 是创建对象的原语。通常,您使用#new,如果您不想要任何特殊的东西,则不实现#initialize,因此将执行#ProtoObject 的空实现。否则,您可以直接发送#basicNew,但您可能不应该这样做。

    干杯

    【讨论】:

    • 虽然有些方言会在new 上发送initialize,但Smalltalk-80 并非如此。
    • 我相信我已经看到人们将初始化代码放在 MyClass 类>>new而不是 MyClass>>initialize 中的示例,如果它们基本上是同时被调用的,你为什么要这样做?
    • @oykuo - >>initialize 被发送到由 >>new 回答的对象(不是消息 >>new 被发送到的对象)。 >>initialize 可以访问在发送 >>new 之前可能不存在的 instVar。 (也许您正在考虑类端初始化?)
    【解决方案2】:

    使用new创建一个新对象,而initialize方法在新对象创建时执行,并初始化对象。

    【讨论】:

      【解决方案3】:

      Bavarious 是正确的。

      Behavior >> new
              "Answer a new instance of the receiver.  If the instance can have indexable variables, it will have 0 indexable variables."
      
              "Primitive fails if the class is indexable."
              <primitive: 70>
              self isVariable ifTrue: [^self new: 0].
              self primitiveFailed
      
      Object >> initialize
          "Initialize the object to its default state. This is typically used in a convention that the class implements the #new method to call #initialize automatically. This is not done for all objects in VisualWorks, but the initialize method is provided  here so that subclasses can call 'super initialize' and not get an exception."
      
          ^self.
      

      【讨论】:

      • 这也对应于 Objective-C 的 alloc-init 模式:myObj := [[NSObject alloc] init]。这并不奇怪,:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2016-02-24
      相关资源
      最近更新 更多