Home  >  Article  >  Backend Development  >  Detailed explanation of the observer pattern of PHP design patterns

Detailed explanation of the observer pattern of PHP design patterns

韦小宝
韦小宝Original
2017-11-15 10:16:551802browse

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!


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

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!

Statement:
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