Detailed explanation of the observer pattern of PHP design patterns

韦小宝
Release: 2023-03-17 14:28:02
Original
1931 people have browsed it

Define a one-to-many dependency relationship between objects, so that whenever the state of an object changes, its related dependent objects are notified and automatically updated. The aliases of the observer pattern include Publish/Subscribe mode, Model/View mode, Source/Listener mode or Dependents mode. Observer pattern is an object behavior pattern. Observer PatternDefine one-to-many dependencies of objects, so that when an object changes state, all its dependencies will be notified and automatically updated!


<?php
/**
 * 观察者模式
 * @author: Mac
 * @date: 2012/02/22
 */

abstract class Pa
{
    private $_observers = array();

    public function register($sub)
    {
    }

    public function trigger()
    {
    }
}

class Paper extends Pa
{ /* 主题    */
    private $_observers = array(); // 存放new的对象

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


    public function trigger()
    {  /*  外部统一访问    */
        if (!empty($this->_observers)) {
            foreach ($this->_observers as $observer) {
                $observer->update();
            }
        }
    }
}

/**
 * 观察者要实现的接口
 */
interface Observerable
{
    public function update();
}

class Subscriber1 implements Observerable //观察者
{
    public function update()
    {
        echo "观察者1收到执行通知 执行完毕\n";
    }
}

class Subscriber2 implements Observerable //观察者2
{
    public function update()
    {
        echo "观察者2收到执行通知 执行完毕\n";
    }
}


/*  测试    */
$paper = new Paper();
$paper->register(new Subscriber1());
$paper->trigger();
Copy after login

The observer pattern is a very frequently used design pattern. Whether it is a mobile application, a web application or a desktop application, the observer pattern is almost everywhere. It provides a way to achieve linkage between objects. A complete solution, the observer pattern can be used in any scenario involving one-to-one or one-to-many object interaction.

Related recommendations:

What you don’t understand about the PHP observer pattern

Code examples of PHP observer pattern

PHP observer pattern

The above is the detailed content of Detailed explanation of the observer pattern of PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template