观察者模式封装

<?php
//开启报错
ini_set("display_errors", "On");
error_reporting(E_ALL | E_STRICT);




//观察者模式


//被观察者
interface  Observed
{
    //注册
    public function attach(Observer $observer);

    //删除
    public function detach(Observer $observer);

    //消息通知
    public function notice();

}



//观察者
interface  Observer
{
    //业务处理
    public function update(Observed $observed);
}



//实现观察者提示逻辑
//发送邮件提示
class Email implements  Observer
{
    public function update(Observed $observed)
    {
        if($observed->getState()==1){
            echo "邮件发送成功<br>";
        }
    }
}

//记录日志
class Log implements  Observer
{
    public function update(Observed $observed)
    {
        if($observed->getState()==1){
            echo "日志记录成功<br>";
        }
    }
}

//发送短信
class Message implements  Observer
{
    public function update(Observed $observed)
    {
        if($observed->getState()==1){
            echo "短信发送成功成功<br>";
        }
    }
}






//生成订单
class  Order  implements Observed
{

    //存储观察者对象
    protected $observers=[];
    //存储订单状态
    protected $state=0;


    /**
     * 注册观察者
     */
    public function attach(Observer $observer)
    {
        $key=array_search($observer,$this->observers);

        if($key===false){
            $this->observers[]=$observer;
        }
    }


    /**
     * 删除观察者
     */
    public function  detach(Observer  $observer)
    {
        $key=array_search($observer,$this->observers);

        if($key!==false){
            unset($this->observers[$key]);
        }
    }


    /**
     * 生成订单
     */
    public function addOrder($state){
        $this->state=$state;

        $this->notice();
    }



    public function notice()
    {
        foreach ($this->observers as $observer){
            $observer->update($this);
        }
    }

    /**
     *
     */
    public function getState(){
        return $this->state;
    }


}


$obj=new Order();

$obj->attach(new Email());
$obj->attach(new  Message());
$obj->attach(new Log());

//生成订单
$obj->addOrder(1);

上一篇:vue源码中的observer运作


下一篇:观察者模式