Factory Sample Code

This article is about the Factory pattern: a class that creates other classes.

The Factory Pattern

Date: 20 Dec 2008

Tha Factory pattern has always a class that creates objects for you , instead of using new directly, you will call your factory class, this factory class has usually a static method (see SongFactory in Listing 1), that means, only one instance of an object, the factory class will decide wich object will create for you.

Listing 1. The Factory pattern



/**
 * Code to demonstrate the Factory pattern
 *
 * 20-Dec-2008
 * @author freedelta http://freedelta.free.fr
 */
 
 
 /**
  * Class base, here we have the common attributes
  * shared by the children classes
  */
 class Song  {
    public $id=null;
    public $songName=null;
    public $author=null;

    public function __construct($id,$songName,$author)
    {
        $this->id=$id;
        $this->songName=$songName;
        $this->author=$author;         
    }
 }
 
 // Child class #1
 class UsSong extends Song
 {
    public $state=null;
    public $zip=null;
   
    public function __construct($id,$songName,$author,$state,$zip)
    {
        parent::__construct($id,$songName,$author);
     
        $this->state=$state;
        $this->zip=$zip;   
    }   
 }

 // Child class #2  class ForeignSong extends Song  {
    public $country=null;
    public $language=null;

    public function __construct($id,$songName,$author,$country,$language)     {
        parent::__construct($id,$songName,$author);       
        $this->country=$country;
        $this->language=$language; 
    }
 }
 
 /**
  * Factory class, this is the class that creates other classes,
  * remember: a method that creates objects it is static
  * so we don't need to use the "new" operator when instatiating this class
  */  
 class SongFactory
 {     public static function createSong($id,$songName,$author,$state,$zip,$country,$language)
    {   
        if($country=="USA")
        {             return new UsSong($id,$songName,$author,$state,$zip);
        }
        else         {             return new ForeignSong($id,$songName,$author,$country,$language);
        }
    }
 }

 // Sample use  $songs=array();

 $songs[]=SongFactory::createSong(1,"Country Roads","J Denver","Colorado","12345","USA","");
 $songs[]=SongFactory::createSong(1,"La vie en rose","some french author","","","France","French");
 
 foreach($songs as $s)
 {
    $class=new ReflectionClass($s);
    print $class->getName()." - ".$s->id." - ".$s->songName." - ".$s->author."\n";

 }