我正在寻找一种好的、干净的方法来解决 PHP5 仍然不支持多重继承的事实。这是类层次结构:
Message
- 短信
-------- 邀请短信
-- 邮件留言
-------- 邀请邮件留言
两种类型的邀请*课程有很多共同点;我希望有一个共同的父类 Invitation,他们都可以继承它。不幸的是,它们与当前的祖先也有很多共同点...... TextMessage 和 EmailMessage。这里是多重继承的经典愿望。
解决该问题的最轻量级方法是什么?
Thanks!
Alex,大多数时候,您需要多重继承,这表明您的对象结构有些不正确。在你概述的情况下,我发现你的阶级责任太广泛了。如果消息是应用程序业务模型的一部分,则它不应该关心渲染输出。相反,您可以分割责任并使用 MessageDispatcher 来发送使用文本或 html 后端传递的消息。我不知道你的代码,但让我这样模拟一下:
$m = new Message();
$m->type = 'text/html';
$m->from = 'John Doe <[email protected]>';
$m->to = 'Random Hacker <[email protected]>';
$m->subject = 'Invitation email';
$m->importBody('invitation.html');
$d = new MessageDispatcher();
$d->dispatch($m);
通过这种方式,您可以向 Message 类添加一些专门化:
$htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor
$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor
$d = new MessageDispatcher();
$d->dispatch($htmlIM);
$d->dispatch($textIM);
请注意,MessageDispatcher 将根据以下情况决定是否以 HTML 或纯文本形式发送type
已传递 Message 对象中的属性。
// in MessageDispatcher class
public function dispatch(Message $m) {
if ($m->type == 'text/plain') {
$this->sendAsText($m);
} elseif ($m->type == 'text/html') {
$this->sendAsHTML($m);
} else {
throw new Exception("MIME type {$m->type} not supported");
}
}
总而言之,责任分为两个类。消息配置在 InvitationHTMLMessage/InvitationTextMessage 类中完成,发送算法委托给调度程序。这称为策略模式,您可以阅读更多内容here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)