Design Pattern : Factory Pattern

Video
This is a Creational Pattern. There are 3 kind of Factory Pattern  –
1. Simple Factory
2. Factory Method
3. Abstract Factory

Simple Factory

The Simple Factory isn’t actually a Design Pattern; it’s more of a programming idiom. Real world example:

Consider, you are building a house and you need doors. You can either put on your carpenter clothes, bring some wood, glue, nails and all the tools required to build the door and start building it in your house or you can simply call the factory and get the built door delivered to you so that you don’t need to learn anything about the door making or to deal with the mess that comes with making it.

In plain words –

Simple factory simply generates an instance for client without exposing any instantiation logic to the client

Wikipedia says

In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be “new”.

Programmatic Example

First of all we have a door interface and the implementation

interface Door {  public function getWidth(): float;  public function getHeight(): float; } class WoodenDoor implements Door {  protected $width;  protected $height;  public function __construct(float $width, float $height)  {  $this->width = $width;  $this->height = $height;  }  public function getWidth(): float  {  return $this->width;  }  public function getHeight(): float  {  return $this->height;  } }

Then we have our door factory that makes the door and returns it –

class DoorFactory {  public static function makeDoor($width, $height): Door  {  return new WoodenDoor($width, $height);  } }

And then it can be used as

// Make me a door of 100x200 $door = DoorFactory::makeDoor(100, 200); echo 'Width: ' . $door->getWidth(); echo 'Height: ' . $door->getHeight(); // Make me a door of 50x100 $door2 = DoorFactory::makeDoor(50, 100);

When to Use?

When creating an object is not just a few assignments and involves some logic, it makes sense to put it in a dedicated factory instead of repeating the same code everywhere.

I’ve seen a similar design where a factory like this is defined as a static method. What is the difference?

Defining a simple factory as a static method is a common technique and is often called a static factory. Why use a static method? Because you don’t need to instantiate an object to make use of the create method.
But remember it also has the disadvantage that you can’t subclass and change the behaviour of the create method.

Screen Shot 2019-09-17 at 9.05.36 AM
From `Head First Design Pattern`


Factory Method

The Factory Method Pattern encapsulates object creation by letting subclasses decide what objects to create. It’s decided at runtime. 

Real world example

Consider the case of a hiring manager. It is impossible for one person to interview for each of the positions. Based on the job opening, she has to decide and delegate the interview steps to different people.

In plain words

It provides a way to delegate the instantiation logic to child classes.

Wikipedia says

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

Programmatic Example

Taking our hiring manager example above. First of all we have an interviewer interface and some implementations for it

interface Interviewer {  public function askQuestions(); } class Developer implements Interviewer {  public function askQuestions()  {  echo 'Asking about design patterns!';  } } class CommunityExecutive implements Interviewer {  public function askQuestions()  {  echo 'Asking about community building';  } }

Now let us create our HiringManager

abstract class HiringManager {  // Factory method  abstract protected function makeInterviewer(): Interviewer;  public function takeInterview()  {  $interviewer = $this->makeInterviewer();  $interviewer->askQuestions();  } } 

Now any child can extend it and provide the required interviewer

class DevelopmentManager extends HiringManager {  protected function makeInterviewer(): Interviewer  {  return new Developer();  } } class MarketingManager extends HiringManager {  protected function makeInterviewer(): Interviewer  {  return new CommunityExecutive();  } }

and then it can be used as

$devManager = new DevelopmentManager(); $devManager->takeInterview(); // Output: Asking about design patterns $marketingManager = new MarketingManager(); $marketingManager->takeInterview(); // Output: Asking about community building.

When to use?

Useful when there is some generic processing in a class but the required sub-class is dynamically decided at runtime. Or putting it in other words, when the client doesn’t know what exact sub-class it might need.

Screen Shot 2019-09-17 at 9.27.14 AM
From `Head First Design Pattern`


 

Abstract Factory  Link

An Abstract Factory gives us an interface for creating a family of products. By writing code that uses this interface, we decouple our code from the actual factory that creates the products. That allows us to implement a variety of factories that produce products meant for different contexts – such as different regions, different operating systems, or different look and feels. Because our code is decoupled from the actual products, we can substitute different factories to get different behaviors.

The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Real world example

Extending our door example from Simple Factory. Based on your needs you might get a wooden door from a wooden door shop, iron door from an iron shop or a PVC door from the relevant shop. Plus you might need a guy with different kind of specialities to fit the door, for example a carpenter for wooden door, welder for iron door etc. As you can see there is a dependency between the doors now, wooden door needs carpenter, iron door needs a welder etc.

In plain words

A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.

Wikipedia says

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes

Programmatic Example

Translating the door example above. First of all we have our Door interface and some implementation for it

interface Door {  public function getDescription(); } class WoodenDoor implements Door {  public function getDescription()  {  echo 'I am a wooden door';  } } class IronDoor implements Door {  public function getDescription()  {  echo 'I am an iron door';  } }

Then we have some fitting experts for each door type

interface DoorFittingExpert {  public function getDescription(); } class Welder implements DoorFittingExpert {  public function getDescription()  {  echo 'I can only fit iron doors';  } } class Carpenter implements DoorFittingExpert {  public function getDescription()  {  echo 'I can only fit wooden doors';  } }

Now we have our abstract factory that would let us make family of related objects i.e. wooden door factory would create a wooden door and wooden door fitting expert and iron door factory would create an iron door and iron door fitting expert

interface DoorFactory {  public function makeDoor(): Door;  public function makeFittingExpert(): DoorFittingExpert; } // Wooden factory to return carpenter and wooden door class WoodenDoorFactory implements DoorFactory {  public function makeDoor(): Door  {  return new WoodenDoor();  }  public function makeFittingExpert(): DoorFittingExpert  {  return new Carpenter();  } } // Iron door factory to get iron door and the relevant fitting expert class IronDoorFactory implements DoorFactory {  public function makeDoor(): Door  {  return new IronDoor();  }  public function makeFittingExpert(): DoorFittingExpert  {  return new Welder();  } }

And then it can be used as

$woodenFactory = new WoodenDoorFactory(); $door = $woodenFactory->makeDoor(); $expert = $woodenFactory->makeFittingExpert(); $door->getDescription(); // Output: I am a wooden door $expert->getDescription(); // Output: I can only fit wooden doors // Same for Iron Factory $ironFactory = new IronDoorFactory(); $door = $ironFactory->makeDoor(); $expert = $ironFactory->makeFittingExpert(); $door->getDescription(); // Output: I am an iron door $expert->getDescription(); // Output: I can only fit iron doors

As you can see the wooden door factory has encapsulated the carpenter and the wooden door also iron door factory has encapsulated the iron door and welder. And thus it had helped us make sure that for each of the created door, we do not get a wrong fitting expert.

When to use?

When there are interrelated dependencies with not-that-simple creation logic involved

 

Screen Shot 2019-09-18 at 9.00.22 AM
From Head First Design Pattern


 

  • All factories encapsulate object creation.
  • Simple Factory, while not a bona fide design pattern, is a simple way to decouple your clients from concrete classes.
  • Factory Method relies on inheritance: object creation is delegated to subclasses which implement the factory method to create objects.
  • Abstract Factory relies on object composition: object creation is implemented in methods exposed in the factory interface.
  • All factory patterns promote loose coupling by reducing the dependency of your application on concrete classes.
  • The intent of Factory Method is to allow a class to defer instantiation to its subclasses.
    The intent of Abstract Factory is to create families of related objects without having to depend on their concrete classes.
  • The Dependency Inversion Principle guides us to avoid dependencies on concrete types and to strive for abstractions.
  • Factories are a powerful technique for coding to abstractions, not concrete classes

 



What is the basic difference between the Factory and Abstract Factory Patterns?

With the Factory pattern, you produce implementations (Apple, Banana, Cherry, etc.) of a particular interface — say, IFruit.
With the Abstract Factory pattern, you produce implementations of a particular Factory interface — e.g., IFruitFactory. Each of those knows how to create different kinds of fruit.

Factory pattern

  • Creational patterns abstract the object instantiation process. They hide how objects are created and help make the overall system independent of how its objects are created and composed.
  • Class creational patterns focus on the use of inheritance to decide the object to be instantiated Factory Method.
  • Object creational patterns focus on the delegation of the instantiation to another object Abstract Factory.

The Abstract Factory Pattern

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

  • The Abstract Factory pattern is very similar to the Factory Method pattern.
  • One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation. Actually, the delegated object frequently uses factory methods to perform the instantiation!

 

One thought on “Design Pattern : Factory Pattern

Leave a comment