PHP设计模式之观察者模式

来源:互联网 发布:官方淘宝斗龙战士宇宙 编辑:程序博客网 时间:2024/04/30 04:02

引导1: 什么是观察者模式?
观察者模式模式也叫消息订阅,作用是一个操作发生变化时,便会围绕这个操作进行一系列的其他操作。

引导2: 应用案例
作为一个没有女朋友的程序员是不是每天只有10086给你发短信 和微信呢?大概是这样,当你一不小心欠费了或者流量超额时,手机上不仅仅会接到短信,而且微信也能接收到消息,甚至还有你的邮箱也会接到详细的消息。更多生活中案例还有信用卡消费后 也会接到短信,微信,邮件等等···········

上代码

<?php/** * Created by PhpStorm. * User: rjj * Date: 2017/7/3 * Time: 22:31 *///通知消息  观察者interface INotice{    function doNotice($msg);}//业务接口   被观察者interface IDeductions{    function addNotice($notice);}class Deductions implements IDeductions{    //存储消息通知    private $_notice = [];    //TODO:这里省略话费检查业务    //发送消息   循环执行已经添加的消息通知业务    public function sendNotice($msg){        foreach($this->_notice as $notice){            $notice->doNotice($msg);        }    }    //添加消息通知类型    public function addNotice($notice)    {        $this->_notice[] =$notice;    }}//短信提醒class MsnNotice implements INotice {    public function doNotice($msg)    {        echo '来至短信提醒:'.$msg.PHP_EOL;    }}//邮箱提醒class EmailNotice implements INotice {    public function doNotice($msg)    {        echo '来至邮箱提醒:'.$msg.PHP_EOL;    }}//微信提醒class WechatNotice implements INotice {    public function doNotice($msg)    {        echo '来至微信提醒:'.$msg.PHP_EOL;    }}$deduction = new Deductions();//添加$deduction->addNotice(new MsnNotice());$deduction->addNotice(new EmailNotice());$deduction->addNotice(new WechatNotice());$deduction->sendNotice('您的手机以欠费');

可能你在别处看到的观察者模式和我的有所不同,不过设计模式并没有十分统一的代码规范,只是一种思想而已,弄懂思维就好,自己也可以用另外的方式来实现!
还请多多指点

原创粉丝点击