It is my understanding that it is difficult to create constructors of classes in Smalltalk and Objective-C. This is because the constructor can't be a message of a class instance because the class Class is not yet defined.
As far as I can te开发者_StackOverflow中文版ll, the solution is to create a new class whose only instance is itself a class. But how does the constructor work in this situation? I don't understand the process.
I'm talking in terms of Smalltalk. There are two types of things that you could reasonably call constructors here. One is the method that initializes a new instance of a class. The other is the things that initializes a class. Neither of them is difficult.
For instance initialization, the convention is that you implement the "new" method on the class as new ^super new initialize (do the superclass's implementation of new, and then send the "initialize" message to the result and return it) Lots of classes may already inherit this implementation, so you just need to write an initialize method as
initialize super initialize. foo := 1. etc.
To initialize a new class, the mechanism is similar. You implement a class method called "initialize", and it will automatically get sent when the class is loaded into a new Smalltalk environment (image).
The solution is to create a method on the class which does all the necessary initialisation of the instance.
精彩评论