2011-04-17 12 views

Respuesta

7

Exactamente. Cuando envía el mensaje #new, no solo crea el objeto, sino que envía el mensaje #initialize. Esto le permite personalizar la inicialización de los objetos. Mira:

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 

Y luego:

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

Y:

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" 

Así que ... # basicNew es la primitiva que crea el objeto. Normalmente, utiliza #new y si no desea nada en especial, no implementa #initialize y, por lo tanto, se ejecutará la implementación vacía de #ProtoObject. De lo contrario, puede enviar directamente #basicNew, pero probablemente no debería hacer esto.

Cheers

+2

Aunque algunos dialectos envían 'initialize' sobre' new', esto no es cierto para Smalltalk-80. –

+0

Creo que he visto ejemplos donde las personas ponen el código de inicialización en la clase MyClass >> nuevo en lugar de MyClass >> initialize, ¿por qué harías eso si se invocan básicamente al mismo tiempo? – oscarkuo

+0

@oykuo - >> initialize se envía al objeto respondido por >> nuevo (no el objeto al que se envió el mensaje >> nuevo). >> initialize tiene acceso a instVars que tal vez no existía antes >> se envió nuevo. (¿Tal vez estás pensando en la inicialización del lado de la clase?) – igouy

5

Con la nueva se crea un nuevo objeto, mientras se ejecuta el método initialize cuando se crea el nuevo objeto, e inicializa el objeto.

3

Bavarious es correcto.

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. 
+0

Esto también corresponde al patrón alloc-init de Objective-C: 'myObj: = [[NSObject alloc] init]'. No es terriblemente sorprendente, eso :) –

Cuestiones relacionadas