Design patterns: Factory Method
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 new kinds of objects doesn’t require changes to the main class.
- 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";
}
}
class CarFactory {
public static function createCar($type) {
if ($type === 'sedan') {
return new Sedan();
} elseif ($type === 'suv') {
return new SUV();
}
throw new Exception("Invalid car type");
}
}
// Usage
$car = CarFactory::createCar('sedan');
echo $car->drive();
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.