Factory Method
8/8/25Less than 1 minute
Description
- Create các object mà không cần chỉ định class cấu trúc.
- Define a method để tạo object thay cho việc dùng operator (new Class).
Example
Send notification
abstract class Notification
{
abstract public function getDriver(): NotificationDriver;
public function send(string $message): void
{
$driver = $this->getDriver();
$driver->connect();
$driver->send($message);
}
}
interface NotificationDriver
{
public function connect(): void;
public function send(string $message): void;
}
Send notification bằng Mail:
class MailNotification extends Notification
{
protected string $mail;
protected string $password;
public function __construct(string $mail, string $password)
{
$this->mail = $mail;
$this->password = $password;
}
public function getDriver(): NotificationDriver
{
return new MailDriver($this->mail, $this->password);
}
}
class MailDriver implements NotificationDriver
{
protected string $mail;
protected string $password;
public function __construct(string $mail, string $password)
{
$this->mail = $mail;
$this->password = $password;
}
public function connect(): void
{
// TODO: Connect mail with mail and password.
}
public function send(string $message): void
{
// TODO: mail send
}
}
Send notification:
class SlackNotification extends Notification
{
public function getDriver(): NotificationDriver
{
return new SlackDriver();
}
}
class SlackDriver implements NotificationDriver
{
public function connect(): void
{
// TODO: Implement connect() method for the slack.
}
public function send(string $message): void
{
// TODO: slack send
}
}
Usage:
$notification = new MailNotification("admin@gmail.com", "123456");
$notification->send("Send notification message for Factory Method example");
Refer: https://refactoring.guru/design-patterns/factory-method/php/example