装饰器模式

类图

2024072116162888.png

代码

<?php
 
interface Notifier {
public function send(string $message);
}
 
class BasicNotifier implements Notifier {
public function send(string $message) {
echo "Sending notification: $message\n";
}
}
 
// 装饰器基类
class NotifierDecorator implements Notifier {
protected $wrapped;
 
public function __construct(Notifier $notifier) {
$this->wrapped = $notifier;
}
 
public function send(string $message) {
$this->wrapped->send($message);
}
}
 
// 具体的装饰器
class SMSNotifier extends NotifierDecorator {
public function send(string $message) {
parent::send($message);
echo "Sending SMS: $message\n";
}
}
 
class EmailNotifier extends NotifierDecorator {
public function send(string $message) {
parent::send($message);
echo "Sending Email: $message\n";
}
}
 
// 使用装饰器模式
$notifier = new BasicNotifier();
$smsNotifier = new SMSNotifier($notifier);
$emailNotifier = new EmailNotifier($smsNotifier);
 
$emailNotifier->send("Hello, World!");