1、定义消息发送器接口:
php
interface MessageSender {
public function send($to, $message);
}
2、实现具体的消息发送器:
邮件发送器:
php
class EmailSender implements MessageSender {
public function send($to, $message) {
echo Sending email to $to: $message\n;
}
}
短信发送器:
php
class SmsSender implements MessageSender {
public function send($to, $message) {
echo Sending SMS to $to: $message\n;
}
}
3、创建工厂类来生成正确的消息发送器:
php
class MessageFactory {
public static function create($type) {
switch ($type) {
case 'email':
return new EmailSender();
case 'sms':
return new SmsSender();
default:
throw new Exception(Unknown message type);
}
}
}