|
Navigation: Appendix B: Dolphin Pattern Book > Method Patterns > Instance Creation Method |
![]() ![]()
|
Context
Some objects require parameterization by the programmer when they are created. This can be achieved by creating a new default instance of the class and then later using its accessor methods to set each of the instance variables individually. However, sometimes a class contains instance variables which are fundamental to its operation or identity, without which a new instance would be considered invalid.
Also Known As
Constructor Method
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 (or super) and then uses an Accessor Method to set the details of the new instance.
Examples
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.
Point class>>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