Creational Patterns: Factory, Builder, Singleton
Control object creation cleanly with creational patterns.
Controlling creation
Creational patterns decouple what you need from how it is built. When construction is conditional, multi-step, or must be centralized, scattering new across the codebase couples callers to concrete classes. Here we cover Factory (and Factory Method), Builder for complex assembly, and Singleton (with its caveats).
Simple Factory
A simple factory centralizes a creation decision behind one method. Callers ask for a logical type and receive a configured concrete instance, without knowing the class names.
<?php
interface Notifier { public function send(string $msg): string; }
final class EmailNotifier implements Notifier {
public function send(string $m): string { return "email: $m"; }
}
final class SmsNotifier implements Notifier {
public function send(string $m): string { return "sms: $m"; }
}
final class NotifierFactory {
public static function make(string $channel): Notifier {
return match ($channel) {
'email' => new EmailNotifier(),
'sms' => new SmsNotifier(),
default => throw new InvalidArgumentException($channel),
};
}
}
echo NotifierFactory::make('sms')->send('Hi'), PHP_EOL;
All lessons in this course
- SOLID Principles in Practice
- Creational Patterns: Factory, Builder, Singleton
- Structural Patterns: Adapter, Decorator, Facade
- Behavioral Patterns: Strategy, Observer, Command