Main Content

Object factories in C++, Python, PHP and Perl

Archive - Originally posted on "The Horse's Mouth" - 2014-12-19 21:27:13 - Graham Ellis

Raw materials are converted into a manufactured product in a factory or by a factory procedure, and the sort of product you can make depends on both the raw material that's supplied and on the capability of the factory.

And so it is with Object Oriented Computer Programming - supply raw material to something that's known as a factory method - that's not a reserved word, by the way, just a convention, and the factory method will return you a object it has manufactured. Since no object exist at the start of the process, your factory method needs to be a class or static method (the naming convention depends on which language you're using).

During today's course, I wrote an example in C++ of a group of two (very small) classes, both inheriting from the same base class, and I provided a factory within that base class to manufacture new objects of the two different types, depening on the incoming data - strings from a file, where the string contents lead to the decision as to which object was manufactured. Complete example [here].

Other examples of factory methods manufacturing different object types are [here] in Python, [here] in PHP and [here] in Perl.