设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 手机 数据
当前位置: 首页 > 站长学院 > PHP教程 > 正文

浅谈PHP面向对象之访问者模式+组合模式(2)

发布时间:2021-01-17 13:44 所属栏目:121 来源:网络整理
导读:private function levy(Unit $unit,$amount){ //主要的业务逻辑 $this-report .= "Tax levied for" . get_class($unit); $this-report .= ": $amount\n"; $this-due +=$amount; } function getReport(){ return $th

  private function levy(Unit $unit,$amount){        //主要的业务逻辑
    $this->report .= "Tax levied for" . get_class($unit);
    $this->report .= ": $amount\n";
    $this->due +=$amount;
  }

  function getReport(){
    return $this->report;
  }

  function getTax(){
    return $this->due;
  }
}

//客户端代码1(获取并输出每个对象的一些信息)
class UnitScript {
  static function joinExisting(Unit $newUnit,Unit $occupyingUnit){
    $comp;
    if(!is_null($com = $occupyingUnit->getComposite())){
      $comp->addUnit($newUnit);
    } else {
      $comp = new Army();
      $comp->addUnit($occupyingUnit);
      $com->addUnit($newUnit);
    }
    return $comp;
  }
}

$main_army = new Army();
UnitScript::joinExisting(new Archer(),$main_army);
UnitScript::joinExisting(new LaserCannonUnit(),$main_army);
UnitScript::joinExisting(new Cavalry(),$main_army);

$textdump = new TextDumpArmyVisitor();
$main_army->accept($textdump);
print $textdump->getText();

//客户端代码2(对每个对象征税,最后输出总共征收了多少)
$main_army = new Army();
UnitScript::joinExisting(new Archer(),$main_army);
$taxcollector = new TaxCollectionVisitor();
$main_army->accept($taxcollector);
print $taxcollector->getTax();

    //上述的代码因为太懒没测试,抱歉! 感兴趣的朋友就自己运行调试一下吧!

以上这篇浅谈PHP面向对象之访问者模式+组合模式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读