Factory
Publié le 3 Mars 2025Factory est un pattern de création, qui permet de créer des objets sans spécifier la classe exacte de l’objet à instancier.
Principe
Exemples d’utilisations
Envoi de notifications à des utilisateurs
Moyens de paiements sur un site de e-commerce
Points d’attentions
Implémenter une factory
Exemple d'utilisation de Factory avec Go
package factory
type Notification interface {
Send(message string)
}
package factory
import "fmt"
type EmailNotification struct{}
func (e EmailNotification) Send(message string) {
// Code pour l'envoi d'email
fmt.Println("Email envoyé :", message)
}
package factory
import "fmt"
type SMSNotification struct{}
func (s SMSNotification) Send(message string) {
// Code pour l'envoi de SMS
fmt.Println("SMS envoyé :", message)
}
package factory
import (
"errors"
"strings"
)
func CreateNotification(notificationType string) (Notification, error) {
switch strings.ToLower(notificationType) {
case "email":
return EmailNotification{}, nil
case "sms":
return SMSNotification{}, nil
default:
return nil, errors.New("type de notification non supporté : " + notificationType)
}
}
package main
import (
"fmt"
"practice/designpatterns/factory-decorticode/factory"
)
func main() {
notification, err := factory.CreateNotification("email")
if err != nil {
fmt.Println(err)
return
}
notification.Send("Envoi du message")
}
Le même exemple en PHP
namespace Practice\DesignPatterns\Factory;
interface NotificationInterface
{
public function send(string $message);
}
namespace Practice\DesignPatterns\Factory;
class EmailNotification implements NotificationInterface {
public function send(string $message) {
// Code pour l'envoi d'emails
echo "Email envoyé : $message";
}
}
namespace Practice\DesignPatterns\Factory;
class SMSNotification implements NotificationInterface {
public function send(string $message) {
// Code pour l'envoi de SMS
echo "SMS envoyé : $message";
}
}
namespace Practice\DesignPatterns\Factory;
use Exception;
class NotificationFactory {
public static function createNotification(string $type): NotificationInterface {
switch (strtolower($type)) {
case 'email':
return new EmailNotification();
case 'sms':
return new SMSNotification();
default:
throw new Exception("Type de notification non supporté : $type");
}
}
}
declare(strict_types=1);
use Practice\DesignPatterns\NotificationFactory;
require "./vendor/autoload.php";
$notification = NotificationFactory::createNotification('email');
$notification->send("Envoi du message");