author:咔咔
wechat:fangkangfk
这个模式,让俩个不相关的类通过观察者模式实现一个功能,个人观点吧!不能为了使用设计模式而强硬使用设计模式,所有的模式都是一样的,他只是一种思想而已
实现步骤:
1.定义一个observer接口
2.定义发送模板消息的类
3.最后就是定义实际运行代码的类payafter
在payafter这个类里边需要注册观察者
<?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();