1. 程式人生 > >【PHP-設計模式】觀察者模式

【PHP-設計模式】觀察者模式

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();