Middle
What is the difference between the 'factory' pattern and the 'factory method'?
sobes.tech AI
Answer from AI
The "Factory" pattern (Simple Factory) is responsible for creating objects of a single type, hiding the logic of their instantiation. It is represented by a separate class or static function that creates and returns a specific object based on input parameters.
<?php
class ProductA {}
class ProductB {}
class ProductFactory
{
public static function createProduct(string $type)
{
switch ($type) {
case 'A':
return new ProductA();
case 'B':
return new ProductB();
default:
throw new \InvalidArgumentException("Invalid product type");
}
}
}
The "Factory Method" pattern is a creational design pattern that defines an interface for creating an object but allows subclasses to decide which class to instantiate. It shifts the responsibility of object creation to subclasses.
<?php
interface Product
{
public function operation(): string;
}
class ConcreteProductA implements Product
{
public function operation(): string
{
return "Result of ConcreteProductA";
}
}
class ConcreteProductB implements Product
{
public function operation(): string
{
return "Result of ConcreteProductB";
}
}
abstract class Creator
{
abstract public function factoryMethod(): Product;
public function someOperation(): string
{
// Call the factory method to create a Product object.
$product = $this->factoryMethod();
// Now, use the product.
return "Creator: The same creator's code has just worked with " . $product->operation();
}
}
class ConcreteCreatorA extends Creator
{
public function factoryMethod(): Product
{
return new ConcreteProductA();
}
}
class ConcreteCreatorB extends Creator
{
public function factoryMethod(): Product
{
return new ConcreteProductB();
}
}
The main differences are:
| Characteristic | "Factory" Pattern (Simple Factory) | "Factory Method" Pattern |
|---|---|---|
| Responsibility | One class or static function creates objects. | Subclasses determine the type of object to create. |
| Flexibility | Limited. Requires changing the factory class when adding new product types. | High. Easily extended by adding new subclasses of creators. |
| Inheritance | Usually not used or used for creating a single factory. | Relies on inheritance to determine what object to create. |
| Level of abstraction | Less abstract. | More abstract. |
| Purpose | Centralized object creation. | Delegating object creation to subclasses. |