Simple Factory Pattern Overview
The Simple Factory Pattern decouples the client code from the object instantaition logic by centralizing creation inside a dedicated factory. The client requests objects from the factory instead of instantiating them directly, which improves maintainability and extensibility.
A key limitation is that adding or modifying product types often requires updating the factory itself, which violates the Open/Closed Principle (open for extension, closed for modification).
Core Interface
<?php
namespace App\Graphics;
interface Renderable
{
public function render(): string;
}
Concrete Implementatiosn
Circle
<?php
namespace App\Graphics;
class CircleShape implements Renderable
{
public function render(): string
{
return 'Rendering a circle';
}
}
Square
<?php
namespace App\Graphics;
class SquareShape implements Renderable
{
public function render(): string
{
return 'Rendering a square';
}
}
Rectangle
<?php
namespace App\Graphics;
class RectangleShape implements Renderable
{
public function render(): string
{
return 'Rendering a rectangle';
}
}
Factory Class
<?php
namespace App\Graphics;
class GraphicFactory
{
public const TYPE_CIRCLE = 'circle';
public const TYPE_SQUARE = 'square';
public const TYPE_RECTANGLE = 'rectangle';
public function create(string $type): ?Renderable
{
switch ($type) {
case self::TYPE_CIRCLE:
return new CircleShape();
case self::TYPE_SQUARE:
return new SquareShape();
case self::TYPE_RECTANGLE:
return new RectangleShape();
default:
return null;
}
}
}
Client Usage
<?php
require_once 'vendor/autoload.php';
use App\Graphics\GraphicFactory;
$factory = new GraphicFactory();
$shape = $factory->create(GraphicFactory::TYPE_CIRCLE);
if ($shape !== null) {
echo $shape->render();
}