php设计模式-观察者模式
2023-09-11 14:19:51 时间
在web应用中,通常,一些小范围的数据和业务的改变,其他相关的业务数据也需要发生改变,这种情况,观察者模式很适合。
观察者模式,通常是通过使用一个叫Observer的接口实现的,如果其他的类要引入观察者,就要实现这个接口
比如,有一个这样的需求,如果产品汇率改变了,所有产品的相关页面展示信息和价格计算也跟着改变
1 interface Observer { 2 function notify( $obj ); 3 } 4 5 class ExchangeRate { 6 static private $instance = NULL; 7 private $observers = array(); 8 private $exchange_rate; 9 10 private function __construct(){ 11 } 12 13 private function __clone(){ 14 } 15 16 public static function getInstance(){ 17 if( self::$instance == NULL ) { 18 self::$instance = new ExchangeRate(); 19 } 20 return self::$instance; 21 } 22 23 public function getExchangeRate(){ 24 return $this->exchange_rate; 25 } 26 27 public function setExchangeRate( $new_rate ){ 28 $this->exchange_rate = $new_rate; 29 //汇率改变,通知所有观察者 30 $this->notifyObservers(); 31 } 32 33 public function registerObservers( $obj ){ 34 $this->observers[] = $obj; 35 } 36 37 public function notifyObservers(){ 38 foreach( $this->observers as $observer ) { 39 //通知观察者 40 $observer->notify( $this ); 41 } 42 } 43 } 44 45 class ProductItem implements Observer { 46 public function __construct(){ 47 //注册成为汇率的观察者 48 ExchangeRate::getInstance()->registerObservers( $this ); 49 } 50 public function notify( $obj ){ 51 if( $obj instanceof ExchangeRate ) { 52 echo "请更新产品的汇率" . PHP_EOL; 53 } 54 } 55 } 56 57 $p1 = new ProductItem(); 58 $p2 = new ProductItem(); 59 60 ExchangeRate::getInstance()->setExchangeRate( 6.2 );
相关文章
- PHP读取大文件的几种方法介绍
- PHP上传(单个)文件示例
- PHP安装模式cgi、fastcgi、php_mod比较
- PHP正则表达式模式修饰符详解
- 为什么我们还会继续使用 PHP ?
- 分享b站PHP学习视频整理
- php:用数组实现多语言(PHP 7.4.2)
- CentOS8平台php日志的定时切分
- Relearning PHP (2) – php 的浮点数float
- PHP 实现适配器(Adapter)模式
- ZenTaoPHP front.class.php
- PHP-5.4.4 安装 APC 启东php-fpm 提示
- 安装 php_mongodb.dll的坑
- [php-src] 理解Php内核中的函数与INI
- [转]XCache 3.0.0 发布,PHP 性能提升方案
- Atitit.使用引擎加脚本架构的设计 使用php,js来开发桌面程序。。
- PHP面试题:PHP加速模式/扩展? PHP调试模式/工具?
- PHP获取POST数据的几种方法汇总
- php去除换行符的方法小结(PHP_EOL变量的使用)