【PHP-设计模式】观察者模式

author:咔咔php

wechat:fangkangfkhtml

 

这个模式,让俩个不相关的类经过观察者模式实现一个功能,我的观点吧!不能为了使用设计模式而强硬使用设计模式,全部的模式都是同样的,他只是一种思想而已设计模式

 

实现步骤:微信

1.定义一个observer接口this

2.定义发送模板消息的类设计

3.最后就是定义实际运行代码的类payaftercode

在payafter这个类里边须要注册观察者server

<?php

header("Content-type: text/html; charset=utf-8");
/**
 * Interface observer
 * 实现观察者角色接口
 */
interface Observer
{
    public function send();
}

/**
 * Class wxpush
 * 最终实现微信模板消息方法
 */
class Wxpush implements observer
{
    public function send()
    {
        echo '最终的发送消息代码';
    }
}

/**
 * Class payafter
 * 修改订单消息
 */
class Payafter
{
    // 定义角色
    private $_ob= [];

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

    /**
     * 实际触发
     */
    public function trigger()
    {
        if(!empty($this->_ob)){
            foreach($this->_ob as $value){
                $value->send();
            }
        }
    }
}

$payafter = new Payafter();

$payafter->register(new Wxpush());

$payafter->trigger();
相关文章
相关标签/搜索