What is a factory method and why use one? - Example in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2010-09-30 07:26:34 - Graham Ellis
How do you create an object? By calling a constructor method, of course.
But ... actually ... there's no "of course" about it. Here's a piece of code from an example I wrote yesterday: sageroll.push Transact::factory(current)
and that call creates an object ...
Whilst you can create an object by directly calling the constructor, in a real-world example you'll often call another method which calls the constructor internally and returns you the instance variable just as a constructor would - and that's known as a factory method. Why use a factory method?
• The data may have arrived in the application in various forms, and the translation necessary to convert it into data that's appropriate for the constructor will logically be written and maintained within the class.
• The incoming data may need examining to see what type of object is actually to be created - so you'll want to use a method which indirectly calls the real constructor, via logic that works out which constructor
• The incoming data may be such that it will create a whole array / hash of objects (or no objects at all) and once again the logic to work this out is logically written and maintained within the class for everyone to use, rather than within each and every application that uses it.
On yesterday's Ruby course, I wrote a sample to tie together many of the features of the OO model into a simple but practical real - world - like example. There's a factory method, comparators, conversion of data from a stream into objects, etc. I didn't go on to multiple families of associated objects - but then I've a lot more to talk about in Ruby as well. The sample code is [here] and the data file that goes with it is [here]. Details of the Ruby course? ... for people who are new to programming - see [here], or if you've programmed before, but in another language, see [here]