The Factory Method is a creational design pattern that provides an interface for creating objects in a class, but lets subclasses decide which object to instantiate. In other words, it moves the instantiation logic of an object from the main class to its subclasses, making the code extensible without modifying existing code.
Characteristics of the Factory Method pattern
- Delegated creation: The main class doesn’t decide which concrete class to instantiate; it delegates that decision to its subclasses.
- Extensibility: Adding a new kind of object only takes a new product and a new concrete creator, without modifying existing code.
- Polymorphism: Subclasses can customize creation behavior without affecting the others.
Example in PHP:
interface Car {
public function drive();
}
class Sedan implements Car {
public function drive() {
return "Driving a sedan";
}
}
class SUV implements Car {
public function drive() {
return "Driving an SUV";
}
}
// Abstract creator: declares the Factory Method
abstract class CarFactory {
abstract public function createCar(): Car;
// Uses the product without knowing which concrete class was created
public function deliverCar() {
$car = $this->createCar();
return "Car delivered. " . $car->drive();
}
}
// Concrete creators: decide which car to instantiate
class SedanFactory extends CarFactory {
public function createCar(): Car {
return new Sedan();
}
}
class SUVFactory extends CarFactory {
public function createCar(): Car {
return new SUV();
}
}
// Usage
function orderCar(CarFactory $factory) {
echo $factory->deliverCar() . "\n";
}
orderCar(new SedanFactory()); // Car delivered. Driving a sedan
orderCar(new SUVFactory()); // Car delivered. Driving an SUV
Explanation
- CarFactory is the abstract creator: it declares the factory method
createCar()and holds the shared logic (deliverCar()), which works only with theCarinterface. - SedanFactory and SUVFactory are the concrete creators: each one overrides
createCar()and decides which class to instantiate. - The client receives a
CarFactoryand callsdeliverCar()without knowing the car’s concrete class. - To add a new kind of car you just create a new product (e.g.
Coupe) and a new creator (e.g.CoupeFactory), without modifying existing code.
Common use case
A common use case is an application that handles different kinds of documents (PDF, Word, etc.). Using the Factory Method, the main DocumentCreator class can delegate the creation of the specific document type (PDFDocument, WordDocument) to its subclasses, which will decide which one to instantiate.