当我们在星际中开地图和几家电脑作战的时候,电脑的几个玩家相当于结盟,一旦我们出兵进攻某一家电脑,其余的电脑会出兵救援。
那么如何让各家电脑知道自己的盟友被攻击了呢?并且自动做出反应?
待解决的问题:一旦某个电脑被我们进攻,其他电脑就获知,并且自动出兵救援。
思路:为电脑设置一些额外的观察系统,由他们去通知其他电脑。
观察者(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 | <?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 ( $oberserver ->name != $beAttackedPlayerName ) $oberserver ->help( $beAttackedPlayerName );
}
}
abstract public function beAttacked( $beAttackedPlayer );
}
class Ally extends abstractAlly {
public function
|
Copy after login