Node:Customizing Instance Creation, Previous:Basic Instance Creation, Up:Creating Instances



3.3.2 Customizing Instance Creation

make itself is a generic function. Hence the make invocation itself can be customized in the case where the new instance's metaclass is more specialized than the default <class>, by defining a make method that is specialized to that metaclass.

Normally, however, the method for classes with metaclass <class> will be applied. This method calls two generic functions:

allocate-instance allocates storage for and returns the new instance, uninitialized. You might customize allocate-instance, for example, if you wanted to provide a GOOPS wrapper around some other object programming system.

To do this, you would create a specialized metaclass, which would act as the metaclass for all classes and instances from the other system. Then define an allocate-instance method, specialized to that metaclass, which calls a Guile primitive C function, which in turn allocates the new instance using the interface of the other object system.

In this case, for a complete system, you would also need to customize a number of other generic functions like make and initialize, so that GOOPS knows how to make classes from the other system, access instance slots, and so on.

initialize initializes the instance that is returned by allocate-instance. The standard GOOPS methods perform initializations appropriate to the instance class.

Similarly, you can customize the initialization of instances of any application-defined class by defining an initialize method specialized to that class.

Imagine a class whose instances' slots need to be initialized at instance creation time by querying a database. Although it might be possible to achieve this a combination of #:init-thunk keywords and closures in the slot definitions, it is neater to write an initialize method for the class that queries the database once and initializes all the dependent slot values according to the results.