2021-11-24 设计模式—— 观察者模式php

观察者模式(Observer),当一个对象的状态发生改变时,依赖他的对象会全部收到通知,并自动更新。

场景:一个事件发生后,要执行一连串更新操作.传统的编程方式,就是在事件的代码之后直接加入处理逻辑,当更新得逻辑增多之后,代码会变得难以维护.这种方式是耦合的,侵入式的,增加新的逻辑需要改变事件主题的代码
观察者模式实现了低耦合,非侵入式的通知与更新机制

观察者类图

image.png

image.png

例子1:一个喂奶小程序
什么时候哭,就什么时候喂奶

<?php
/**
 * 小孩类
 *
 * Class Child
 */
class Child
{
    private $cry = false;
    public function isCry()
    {
        return $this->cry;
    }
    // 睡醒了就 开始哭
    public function wakeUp()
    {
        $this->cry = true;
        return '饿了 5555555';
    }
}

/***
 * 主程序
 *
 * Class Main
 */
class Main
{
    public static function main()
    {
        $child = new Child();

        if (!$child->isCry()) {
           return '开始喂奶';
        }
    }
}
2步 : 加入一个观察者,比如他 父亲
<?php
/**
 * 小孩类
 *
 * Class Child
 */
class Child
{
    private $cry = false;
    private $dad ;
    public function __construct()
    {
        $this->dad = new Dad();

    }

    public function isCry()
    {
        return $this->cry;
    }
    // 睡醒了就 开始哭
    public function wakeUp()
    {
        $this->cry = true;
        echo '饿了 5555555'.'<br>';
        $this->dad->feed();
    }
}

/**
 * 加入观察者
 * Class Dad
 */
class Dad
{
    public function feed()
    {
        echo '我的小孩开始哭了,开始喂奶'.'<br>';
    }
}


/***
 * 主程序
 *
 * Class Main
 */
class MainAct
{
    public static function main()
    {
        $child = new Child();
        $child ->wakeUp();
    }
}

$main = new MainAct();
$main ->main();



3步:接下来我们加入更多的观察者

<?php
/**
 * 小孩类
 *
 * Class Child
 */
class Child
{

    private $cry = false;
    private $dad ;
    private $mum ;
    private $dog ;
    public function __construct()
    {
        $this->dad = new Dad();
        $this->mum = new Mum();
        $this->dog = new Dog();
    }

    public function isCry()
    {
        return $this->cry;
    }

    // 睡醒了就 开始哭
    public function wakeUp()
    {
        $this->cry = true;
        echo '饿了 5555555'.'<br>';
        $this->dad->feed();
        $this->mum->feed();
        $this->dog->feed();
    }
}

/**
 * 加入观察者
 * Class Dad
 */
class Dad
{
    public function feed()
    {
        echo '我的小孩开始哭了,开始喂奶'.'<br>';
    }
}


class Mum
{
    public function feed()
    {
        echo '我的小宝贝开始哭了,赶紧抱抱'.'<br>';
    }
}

class Dog
{
    public function feed()
    {
        echo '小主人开始哭了,汪汪汪'.'<br>';

    }
}

/***
 * 主程序
 *
 * Class Main
 */
class MainAct
{
    public static function main()
    {
        $child = new Child();
        $child ->wakeUp();
    }
}

$main = new MainAct();
$main ->main();

者就是最简单的观察者原理,但是这种观察。如果要添加新的 观察者很麻烦。而且,观察者的反应不一定要耦合在某个特定的观察事件中。
比如,小孩哭了狗 汪汪叫。不一定要小孩哭了狗才叫,狗看到猫了,也旺旺叫。所以,上述方法不太灵活,而且耦合度高。
4步:由此,我们抽象出来了一个 observe(观察者)

<?php
/**
 * 小孩类
 *
 * Class Child
 */
class Child
{

    private $cry = false;
    private $dad ;
    private $mum ;
    private $dog ;
    public function __construct()
    {
        $this->dad = new Dad();
        $this->mum = new Mum();
        $this->dog = new Dog();
    }

    public function isCry()
    {
        return $this->cry;
    }

    // 睡醒了就 开始哭
    public function wakeUp()
    {
        $this->cry = true;
        echo '饿了 5555555'.'<br>';
        // 遍历
        $this->dad->activeOnWakeUp();
        $this->mum->activeOnWakeUp();
        $this->dog->activeOnWakeUp();
    }
}

/**
 * 观察者方法
 * Interface Observe
 */
interface Observe{
    public function activeOnWakeUp();
}

/**
 * 加入观察者
 * Class Dad
 */
class Dad implements Observe
{
    public function activeOnWakeUp()
    {
        $this->feed();
    }

    public function feed()
    {
        echo '我的小孩开始哭了,开始喂奶'.'<br>';
    }
}


class Mum implements Observe
{
    public function activeOnWakeUp()
    {
        $this->feed();
    }

    public function feed()
    {
        echo '我的小宝贝开始哭了,赶紧抱抱'.'<br>';
    }
}

class Dog implements Observe
{
    public function activeOnWakeUp()
    {
        $this->feed();
    }

    public function feed()
    {
        echo '小主人开始哭了,汪汪汪'.'<br>';

    }
}

/***
 * 主程序
 *
 * Class Main
 */
class MainAct
{
    public static function main()
    {
        $child = new Child();
        $child ->wakeUp();
    }
}

$main = new MainAct();
$main ->main();

由于,哭的过程中可能出现不同状况的哭。比如是摔倒了哭,是玩具被抢了哭。也有中午哭,晚上哭。等等
所以观察者,需要对被观察者的行为,做出不同的反应。
为此,我们就需要抽象出一个类,叫事件类:WakeUPEvent

把事件状况作为参数,传入对于的观察情况之中; 观察者根据事件情况,做出对应反应。

由此,我们对child 抽象出来,作为一个抽象的被观察者。 把事件,作为抽象主体。整个观察者模式完成

观察者模式 -- 标准参考

<?php
/**
 * 抽象的被观察者
 *
 * 定义一个观察者数组,并实现增、删及通知操作。它的职责很简单,就是定义谁能观察,谁不能观察
 *
 * 定义一个强制子类必须执行方法
 *
 * Class ConcreteObserver
 */
abstract class ConcreteObserver
{

    /**
     * @var array  保存所有已注册的观察者
     */
    private $observers = [];


    /**
     * 事件触发(强制要求子类定义该方法)
     *
     * @return mixed
     */
    abstract public function trigger();

    /**
     * 添加观察者
     *
     * @param Observer $observer 观察者对象
     * @return bool
     */
    public function attach(Observer $observer)
    {
        return array_push($this->observers, $observer);  //array_push() 向数组尾部插入
    }

    /**
     * 移除观察者
     *
     * @param Observer $observer 观察者对象
     * @return bool
     */
    public function detach(Observer $observer)
    {
        //检查观察者是否在观察者数组中,返回索引值
        $index = array_search($observer, $this->observers);  //array_search()在数组中搜索键值,并返回它的键名:
        if ($index === false || array_key_exists($index, $this->observers)) return false;  // array_key_exists() 查键名是否存在于数组中:
        unset($this->observers[$index]);
        return true;
    }


    /**
     * 广播通知以注册的观察者,对注册树进行遍历,让每个对象实现其接口提供的操作
     *
     * @return bool
     */
    public function notify()
    {
        if (!is_array($this->observers)) return false; // 观察者不存在
        foreach ($this->observers as $observer) {      // 遍历已经注册的观察者
            $observer->update();
        }
        return true;
    }
}


/**
 * 抽象观察者Observer
 *
 * 观察者一般是一个接口,每一个实现该接口的实现类都是具体观察者。
 *
 * Interface Observe
 */
interface ObServer
{
    public function update($active = null);
}


/**
 * 具体观察者1
 *
 * Class ObServer1
 */
class ObServer1 implements ObServer
{
    private $active;

    public function __construct($active = null)
    {
        $this->active = $active;
    }

    public function update($active = null)
    {
        echo $this->active . "收到执行通知 执行完毕!<br/>";
    }
}

/**
 * 具体观察者2
 *
 * Class ObServer2
 */
class ObServer2 implements ObServer
{
    private $active;

    public function __construct($active = null)
    {
        $this->active = $active;
    }


    public function update($active = null)
    {
        echo $this->active . "收到执行通知 执行完毕!<br/>";

    }
}


/**
 * 事件  比如 天亮了
 * Class Event
 */
class Event extends ConcreteObserver
{
    private $event_info;  // 事件名称

    public function __construct($event_info = null)
    {
        $this->event_info = $event_info;
    }

    /**
     * 触发事件
     */
    public function trigger()
    {
        echo $this->event_info . " 事件发生,开始干事情了<br/>";
        //通知观察者
        $this->notify();
    }
}


//创建一个事件
$event = new Event('天亮了');
//为事件增加旁观者(注册观察者)  使用注册的方式,是为了对 观察者和被观察 进行解耦
$event->attach(new ObServer1('张三,起来除草'));
$event->attach(new ObServer2('李四,起来施肥'));
//执行事件 通知旁观者
$event->trigger();
//通知完毕,注销观察者
$event->detach(new ObServer1());
$event->detach(new ObServer2());

//---------------------------------------------- 分割线 -------------------------------------------
/**
 * 新增一个 中午的事件
 *
 * Class EventNoon
 */
class EventNoon extends ConcreteObserver
{

    private $event_info;  // 事件名称

    public function __construct($event_info = null)
    {
        $this->event_info = $event_info;
    }

    /**
     * 触发事件
     */
    public function trigger()
    {
        echo $this->event_info . " 事件发生,开始干事情了<br/>";
        //通知观察者
        $this->notify();
    }
}

//创建一个 中午事件
$eventNoon = new EventNoon('中午了');
//为事件增加旁观者(注册观察者)  使用注册的方式,是为了对 观察者和被观察 进行解耦
$eventNoon->attach(new ObServer1('张三,去生火'));
$eventNoon->attach(new ObServer2('李四,淘米'));
//执行事件 通知旁观者
$eventNoon->trigger();
//通知完毕,注销观察者
$event->detach(new ObServer1());
$event->detach(new ObServer2());

参考链接:
https://www.cnblogs.com/chrdai/p/11184221.html
https://www.cnblogs.com/onephp/p/6108344.html
https://blog.csdn.net/root_admin_12138/article/details/82250824
https://www.jianshu.com/p/d55ee6e83d66
https://www.cnblogs.com/adamjwh/p/10913660.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。