Main Content

What is a factory?

Archive - Originally posted on "The Horse's Mouth" - 2010-04-26 17:02:41 - Graham Ellis

A Factory is somewhere that takes raw material, and converts into objects of some value. And so it is in Object Oriented Programming, where a "factory method" takes a chunk of raw material and makes an object out of it. It may differ from a constructor in that we may not know what type of object we're actually going to make when we call it!

Let's see an example (in PHP). Here's some source code which takes each of the lines from an incoming data file and passes them in turn into a factory method. The factory return an object each time it's called, which is stored into an array called options.

$southbound = file("southbound.txt");
$options = array();
foreach ($southbound as $lyne) {
   array_push($options,pubtrans::myfactory($lyne));
   }


From that application code, you can't tell what types of objects have been set up, nor can you tell how the code has decided which to set up - it's all encapsulated (hidden) within the factory.

Here's the code within the pubtrans class / namespace:

static function myfactory($lyne) {
  list($dep_t,$capa,$run_t,$dest,$wotsit) = explode(" ",trim($lyne));
  if ($wotsit == "train") {
    return (new train($dep_t,$capa,$run_t,$dest));
  } else {
    return (new bus($dep_t,$capa,$run_t,$dest));
  }
}


... and from that you can see that we're making either a train or a bus (they are probably classes that are subclasses of pubtrans, but not necessarily so).

The complete example is online - [source code] and [running example]. The data is [here].