In the factory template, we instantiate some subclass without naming it. Consider the pizza factory and the hierarchy:
Pizza PepperoniPizza CheesePizza ...
We would like to create an instance of the pizza subclass without knowing its class name. For instance:
pizza := Pizza flavor: 'cheese' size: 12 inches
responds to the right subclass of pizza, with filled size.
Now in Java or C ++ one could make a large switch statement to compare with different string names. Each time we add a new Pizza subclass, we need to remember to add the main switch to the operator. See Wikipedia article for typical examples.
Not so in Smalltalk, where the classes are first-class objects, so we can iterate the class hierarchy by setting the correspondence of each subclass. For instance:
Pizza class>>flavor: aString size: anInteger matchingClass := self subclasses detect: [:first | first matching: aString]. ^matchingClass new size: anInteger.
And whenever we implement a new pizza subclass, we will implement one method to perform a factory match:
CheesePizza class>>matching: aString ^aString = 'cheese' PepperoniPizza class>>matching: aString ^aString = 'pepperoni'
There is no central operator instruction to maintain. Just objects!
source share