Category Archives: Factory Pattern

Factory Pattern – Design Pattern

Factory Pattern Method encapsulates object creation. The factory method encapsulate object creation by letting subclasses decide what objects to create.


One thing to notice here, class being called(in our case concreteProduct) for instantiating the Object is independent of class that is calling, means to say both of them are unknown to each other, they know only the contract(in our case Product ), with which they will be interacting, Here product interface is contract that is known to both of them, but createrClass does not know that It is interacting with concreteProduct class object, it only know that object which it got from its subclass factory is of type Product, Rest information about object is encapsulated here.

<?php

class createrClass{
    
      function factoryMethod() ;  --> Abstract method
      
      function anOperation()
      {
          
      }
}

class concreteCreator extends createrClass{
        
    //implemented method (responsible for creating objects)
    function factoryMethod()
    {
    }

}

//Interface For concreteProduct class,
interface Product{

}


//class for Object being created by subclass(concreteCreator) method factoryMethod 
class concreteProduct implements Product{ 
 
}

All type of concreteProduct subclasses must implement this interface so that concreteCreator’s factoryMethod only has to know about Product interface type and no more info about subclass that is being instantiated to create Object of specific type

Hope it makes clear picture about factory pattern.