Factory Method Pattern

Software Design Patterns are solutions to common problems that can be applied when developing software. They are well known and understood solutions to regular programming problems.

The factory method pattern is a design pattern for creating objects. The factory is responsible for creating objects, that is, using the new keyword. Every time you create objects of a certain type you delegate the task to the factory.

Lets say we have a system that can invite contacts from different email providers. The factory code would look like something like this in PHP:

class InviterFactory
{
  public static function getInviter($type)
  {
    switch ($type)
    {
    case 'gmail':
      $inviter = new GmailInviter();
      break;
    case 'hotmail':
      $inviter = new HotmailInviter();
      break;
    case 'yahoo':
      $inviter = new YahooInviter();
      break;
    default:
      $inviter = null;
    }

    return $inviter;
  }
}

In the future, if we ever add another email provider, say, canada.com, we would only have to add the CanadaInviter to the factory class, and our whole project is now ready to use this type of inviter.

The factory pattern is also good for unit testing. In unit testing we want to completely be able to control a small section of the program to test all possible inputs and outputs. When testing a section of code that uses the factory to create objects, we can replace the standard factory with a unit-test factory, that returns dummy objects with only enough functionality required for testing that component.

Factory methods promote encapsulation. In our example each of the inviters have the same functionality to retrieving a contact list from the provider, but implement it differently.

interface Inviter
{
  public function getContacts();
}

class GmailInviter implements Inviter
{
  public function getContacts()
  {
    // code to get contacts
    return $contacts;
  }
}

class HotmailInviter implements Inviter
{
  public function getContacts()
  // ...
}

Now you can add the factory pattern to your programming tool belt. Note, this is just example code, real code has comments and error checking.