Pattern: Instance Creation


Context

Some objects require initialisation by the programmer when they are created. This can be achieved by creating a new instance of the class and then using its accessor methods to set each of the instance variables. However, sometimes a class contains instance variables which are fundamental to its operation or identity, without which a new instance would be considered invalid.

Solution

Implement an instance creation class method which is passed initial values for the identity instance variables, and answers an instance of the class containing those details. This method typically sends the #new message to the class and then uses the Accessor Methods to set the details of the new instance.

Example

Consider a class IndexEntry (with instance variables description and page) which represents an entry in a book index. It seems unlikely that a programmer would create an instance of IndexEntry without immediately setting its details. IndexEntry would supply an instance creation method #description:page: which answers a new instance of IndexEntry with the details supplied by the caller.

description: aString page: anInteger
        "Answer a new instance of IndexEntry
        with description aString and page anInteger." 

        ^self new
	        description: aString;
        	page: anInteger;
        	yourself 

Known Uses

The Point class offers an instance creation method #x:y: which answers a new instance of Point with x and y initialized from the parameters.

x: xCoord y: yCoord
        "Answer a new instance of the receiver with the specified
        x and y coordinates"

        ^self basicNew x: xCoord y: yCoord

Related Patterns