其他分享
首页 > 其他分享> > 设计模式十:观察者模式

设计模式十:观察者模式

作者:互联网

观察者模式:

  对个对象依赖于一个对象。当一个对象改变时,所有依赖它的对象都会获得通知和改变。发布订阅。

<?php

/**
 * 小说更新接口
 */
interface StoryUpdateInterface{
    public function update($name);
}

class StoryUpdate implements StoryUpdateInterface{
    public function update($name)
    {
        echo "{$name}小说更新之后".PHP_EOL;
    }
}


 /**
  * 消息发送接口
  */
interface SendMsgInterface{
    public function send($name,$storyName);
}

class SendMsg implements SendMsgInterface{
    public function send($name,$storyName)
    {
        echo "短信:{$name}你好,{$storyName}小说更新了".PHP_EOL;
    }
}

class SendEmail implements SendMsgInterface{
    public function send($name,$storyName)
    {
        echo "邮件:{$name}你好,{$storyName}小说更新了".PHP_EOL;
    }
}

/**
 * 观察者模式-》
 */
abstract class StoryUpdateAbstract{
    private $Observer;

    //注册观察者
    public function register(SendMsgInterface $obj){
        $this->Observer[] = $obj;
    }

    //消息发送
    public function notify($name,$storyName){
        foreach($this->Observer as $obj){
            $obj->send($name,$storyName);
        }
    }
}

/**
 * 客户端
 */
class Story extends StoryUpdateAbstract{

    private $story;
    private $notify_arr=[];
    
    public function __construct(StoryUpdateInterface $story,array $notify_arr)
    {
        $this->story = $story;    
        $this->notify_arr = $notify_arr;
    }

    public function StoryUpdate($storyName){
        $this->story->update($storyName);
        foreach($this->notify_arr as $name){
            $this->notify($name,$storyName);
        }
        
    }
}

$storyUpdate = new StoryUpdate();
$list = ['小张','小王','莉拉','doris'];
$story = new Story($storyUpdate,$list);
$story->register(new SendMsg());//添加观察者
$story->register(new SendEmail());//添加观察者
$story->StoryUpdate('霸道总裁');

 

标签:story,storyName,name,arr,观察者,模式,notify,new,设计模式
来源: https://www.cnblogs.com/wish-yang/p/15190069.html