Explain the Factory pattern

The Factory pattern is a creational design pattern used to create objects. It provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact type of the object to be created isn't known until runtime.

Key Benefits of Using Factory Pattern

  • Encapsulation of Object Creation: It centralizes the creation of objects, thus hiding the specifics from the client code.
  • Flexibility: New types can be added without altering the existing code, adhering to the Open/Closed Principle of object-oriented design.
  • Decoupling: It reduces the dependency of the client code on concrete classes, leading to more maintainable and scalable code.

Example of Factory Pattern in PHP

<?php interface Product { public function getType(); } class ConcreteProductA implements Product { public function getType() { return "Product A"; } } class ConcreteProductB implements Product { public function getType() { return "Product B"; } } class Factory { public static function createProduct($type) { switch($type) { case 'A': return new ConcreteProductA(); case 'B': return new ConcreteProductB(); default: throw new Exception("Product type not recognized."); } } } // Usage $productA = Factory::createProduct('A'); echo $productA->getType(); // Outputs "Product A" $productB = Factory::createProduct('B'); echo $productB->getType(); // Outputs "Product B" ?>

Factory Pattern Creational Design Pattern Object Creation PHP Design Patterns Software Design