Home  >  Article  >  php教程  >  星际争霸之php观察者模式

星际争霸之php观察者模式

WBOY
WBOYOriginal
2016-06-07 17:23:111136browse

当我们在星际中开地图和几家电脑作战的时候,电脑的几个玩家相当于结盟,一旦我们出兵进攻某一家电脑,其余的电脑会出兵救援。


那么如何让各家电脑知道自己的盟友被攻击了呢?并且自动做出反应?


待解决的问题:一旦某个电脑被我们进攻,其他电脑就获知,并且自动出兵救援。


思路:为电脑设置一些额外的观察系统,由他们去通知其他电脑。



观察者(Observer)模式示例:

<?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 
Statement:
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