Factory / Abstract Factory confusion Factory / Abstract Factory confusion php php

Factory / Abstract Factory confusion


The difference between Factory and Abstract Factory is pretty simple. In the latter, the factory itself is abstract (!) and cannot be instantiated directly, but must be sub-classed.

Per example, Factory:

class Document {   public function createPage() {       return new Page;   }}class LandscapeDocument extends Document {   public function createPage() {       return new LandscapePage;   }}

In Abstract Factory:

abstract class Document {   abstract public function createPage();}class PortraitDocument extends Document {   public function createPage() {      return new PortraitPage;   }}class LandscapeDocument extends Document {   public function createPage() {      return new LandscapePage;   }}

In short, the Factory pattern has a default implementation in the factory class itself. The Abstract Factory requires all sub-classes to implement their own version of the factory methods.

That's all there is to it.


Here is another way you can look at it:

To clear the bushes:
A factory pattern is a creational pattern. That is it is used to create instances for use.

Factory Pattern

  • A creational pattern where the logic for creating the instance lies in the hands of the Factory class.
  • A Factory Pattern creates only one type of object instance. In your case it would create objects of type LibraryObject assuming that the LibraryObject is top most object in the hierarchy tree.

Abstract Pattern (Factory of Factories)

  • A creational pattern where the logic for creating the instance lies in the hands of the classes that implement the Factory interface / abstract class.
  • An Abstract Factory pattern can create objects of different types, so you can use the concrete implementations of Factory interface / abstract class to create objects of the types that you desire. That is why it is called a Factory of Factories.

A good reference would be this link below, I would suggest you read the Factory Method pattern as well:
http://www.oodesign.com/creational-patterns/