Code examples of PHP observer pattern

黄舟
Release: 2023-03-06 16:48:02
Original
1299 people have browsed it

PHPObserver patternCode example

<?php
// 观察者模式

/**
 * abstract subject
 */
interface Subject
{
	/**
	 * add Observer
	 */
	public function attach(Observer $obs);
	
	/**
	 * remove Observer
	 */
	public function detach(Observer $obs);
	
	/**
	 * notify Observer
	 */
	public function notify();
}

interface Observer
{
	public function update(Subject $sub);
}

/**
 * concrete subject
 */
class ConcreteSubject implements Subject
{
	private $observerList = array();
	
	public function attach(Observer $obs) {
		$this->observerList[] = $obs;
	}
	
	public function detach(Observer $obs) {
		$this->observerList = array_diff($this->observerList, [$obs]);
	}
	
	public function notify() {
		foreach($this->observerList as $ol) {
			$ol->update($this);
		}
	}
	
	public function doAct() {
		echo &#39;DoAct ... <br/>&#39;;
		$this->notify();
	}
}

/**
 * concrete observer 1
 */
class Observer1 implements Observer
{
	public function update(Subject $sub) {
		echo &#39;Observer one updated! <br/>&#39;;
	}
}

/**
 * concrete observer 2
 */
class Observer2 implements Observer
{
	public function update(Subject $sub) {
		echo &#39;Observer two updated! <br/>&#39;;
	}
}

// test code
$sub = new ConcreteSubject();

$sub->attach(new Observer1()); //add observer
$sub->attach(new Observer1());
$sub->attach(new Observer2());

$sub->doAct();
Copy after login

The above is the detailed content of Code examples of PHP observer pattern. 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