Small equivalent of factory method?

Are factory methods used in Smalltalk, and if so, how should I write, for example, as opposed to how they were in Java? Thanks.

+4
source share
2 answers

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!

+11
source

First of all, you called constructors in Smalltalk. In fact, classes are objects, and "constructors" are simply methods defined in the class that return new instances. Many ways to use factory methods in other languages ​​can be covered in this way.

for instance

 Thing class >> withName: aString ^ dictionaryOfAllThings at: aString ifAbsentPut: (self new name: aString; yourself) 

who receives a thing by name and creates only a new thing if a thing with that name does not exist yet.

0
source

Source: https://habr.com/ru/post/1313915/


All Articles