php设计模式 Observer(观察者模式)

 2025-01-15  阅读 357  评论 8  点赞 108

摘要:复制代码 代码如下:
复制代码 代码如下:

<?php
/**
* 观察者模式
*
* 定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新
* 能够便利地创建查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能
* 插件系统
*/
class observerable
{
private $_observers = array();

public function registerobserver($observer)
{
$this->_observers[] = $observer;
}

public function removeobserver($observer)
{
$key = array_search($observer,$this->_observers);
if(!($key === false))
{
unset($this->_observers[$key]);
}
}

public function notifyobservers()
{
foreach($this->_observers as $observer)
{
if($observer instanceof observer) $observer->update($this);
}
}
}

interface observer
{
public function update($observer);
}

interface displayelement
{
public function display();
}

// -- 实例类定义
class newsobserverable extends observerable
{
private $_sports_news;
public function setsportsnews($data)
{
$this->_sports_news = $data;
$this->notifyobservers();
}

public function getsportsnews()
{
return $this->_sports_news;
}

private $_local_news;
public function setlocalnews($data)
{
$this->_local_news = $data;
$this->notifyobservers();
}

public function getlocalnews()
{
return $this->_local_news;
}
}

class sportsnews implements observer,displayelement
{
private $_data = null;
public function update($observer)
{
if($this->_data != $observer->getsportsnews())
{
$this->_data = $observer->getsportsnews();
$this->display();
}
}

public function display()
{
echo $this->_data.date("y-m-d h:i:s")."<br/>";
}
}

class localnews implements observer,displayelement
{
private $_data = null;
public function update($observer)
{
if($this->_data != $observer->getlocalnews())
{
$this->_data = $observer->getlocalnews();
$this->display();
}
}

public function display()
{
echo $this->_data.date("y-m-d h:i:s")."<br/>";
}
}

// -- 实例化 ---

$objobserver = new newsobserverable();
$local = new localnews();
$sports = new sportsnews();

$objobserver->registerobserver($local);
$objobserver->registerobserver($sports);

$objobserver->setsportsnews("sports news 1 ");
$objobserver->setlocalnews("local news 1 ");
$objobserver->removeobserver($sports);
$objobserver->setlocalnews("local news 2 ");
$objobserver->setsportsnews("sports news 2 ");
$objobserver->removeobserver($local);
$objobserver->setlocalnews("local news 3 ");


标签:phpphp教程

评论列表:

  •   xiaoming22
     发布于 4天前回复该评论
  • 又学到了新知识!
显示更多评论

发表评论:

管理员

承接各种程序开发,外贸网站代运营,外贸网站建设等项目
  • 内容2460
  • 积分67666
  • 金币86666

Copyright © 2024 LS'Blog-保定PHP程序员老宋个人博客 Inc. 保留所有权利。 Powered by LS'blog 3.0.3

页面耗时0.0283秒, 内存占用1.94 MB, 访问数据库28次

冀ICP备19034377号