本文实例讲述了php设计模式之观察者模式。分享给大家供大家参考,具体如下:
当我们在星际中开地图和几家电脑作战的时候,电脑的几个玩家相当于结盟,一旦我们出兵进攻某一家电脑,其余的电脑会出兵救援。
那么如何让各家电脑知道自己的盟友被攻击了呢?并且自动做出反应?
待解决的问题:一旦某个电脑被我们进攻,其他电脑就获知,并且自动出兵救援。
思路:为电脑设置一些额外的观察系统,由他们去通知其他电脑。
观察者(Observer)模式示例:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
<?php
//抽象的结盟类
abstract class abstractAlly
{
//放置观察者的集合,这里以简单的数组来直观演示
public $oberserverCollection ;
//增加观察者的方法,参数为观察者(也是玩家)的名称
public function addOberserver( $oberserverName )
{
//以元素的方式将观察者对象放入观察者的集合
$this ->oberserverCollection[] = new oberserver( $oberserverName );
}
//将被攻击的电脑的名字通知各个观察者
public function notify( $beAttackedPlayerName )
{
//把观察者的集合循环
foreach ( $this ->oberserverCollection as $oberserver )
{
//调用各个观察者的救援函数,参数为被攻击的电脑的名字,if用来排除被攻击的电脑的观察者
if ( $oberserver ->name != $beAttackedPlayerName )
{
$oberserver ->help( $beAttackedPlayerName );
}
}
}
abstract public function beAttacked( $beAttackedPlayer );
}
//具体的结盟类
class Ally extends abstractAlly
{
//构造函数,将所有电脑玩家的名称的数组作为参数
public function __construct( $allPlayerName )
{
//把所有电脑玩家的数组循环
foreach ( $allPlayerName as $playerName )
{
//增加观察者,参数为各个电脑玩家的名称
$this ->addOberserver( $playerName );
}
}
//将被攻击的电脑的名字通知各个观察者
public function beAttacked( $beAttackedPlayerName )
{
//调用各个观察者的救援函数,参数为被攻击的电脑的名字,if用来排除被攻击的电脑的观察者
$this ->notify( $beAttackedPlayerName );
}
}
//观察者的接口
interface Ioberserver
{
//定义规范救援方法
function help( $beAttackedPlayer );
}
//具体的观察者类
class oberserver implements Ioberserver
{
//观察者(也是玩家)对象的名字
public $name ;
//构造函数,参数为观察者(也是玩家)的名称
public function __construct( $name )
{
$this ->name = $name ;
}
//观察者进行救援的方法
public help( $beAttackedPlayerName )
{
//这里简单的输出,谁去救谁,最后加一个换行,便于显示
echo $this ->name. " help " . $beAttackedPlayerName . "<br>" ;
}
abstract public function beAttacked( $beAttackedPlayer );
}
//假设我一对三,两家虫族,一家神族
$allComputePlayer = array ( 'Zerg1' , 'Protoss2' , 'Zerg2' );
//新建电脑结盟
$Ally = new Ally( $allComputePlayer );
//假设我进攻了第二个虫族
$Ally ->beAttacked( 'Zerg2' );
?>
|
用途总结:观察者模式可以将某个状态的变化立即通知所有相关的对象,并调用对方的处理方法。
实现总结:需要一个观察者类来处理变化,被观察的对象需要实现通知所有观察者的方法。
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://www.cnblogs.com/davidhhuan/p/4248205.html
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 28
-
2025-05-25 65
-
PHP实现的mysql操作类【MySQL与MySQLi方式】
2025-05-29 58 -
创建站点时报错:PHP版本不兼容,应该如何选择合适的PHP版本?
2025-05-27 53 -
2025-05-29 47
热门评论