PHP设计模式之解释器(Interpreter)模式入门与应用(3)

咱最后再分享一个实例,如下:

<?php
header("Content-type:text/html;Charset=utf-8");
 
//环境角色,定义要解释的全局内容
class Expression{
 public $content;
 function getContent(){
  return $this->content;
 }
}
 
//抽象解释器
abstract class AbstractInterpreter{
 abstract function interpret($content);
}
 
//具体解释器,实现抽象解释器的抽象方法
class ChineseInterpreter extends AbstractInterpreter{
 function interpret($content){
  for($i=1;$i<count($content);$i++){
   switch($content[$i]){
   case '0': echo "没有人<br>";break;
   case "1": echo "一个人<br>";break;
   case "2": echo "二个人<br>";break;
   case "3": echo "三个人<br>";break;
   case "4": echo "四个人<br>";break;
   case "5": echo "五个人<br>";break;
   case "6": echo "六个人<br>";break;
   case "7": echo "七个人<br>";break;
   case "8": echo "八个人<br>";break;
   case "9": echo "九个人<br>";break;
   default:echo "其他";
   }
  }
 }
}
class EnglishInterpreter extends AbstractInterpreter{
 function interpret($content){
  for($i=1;$i<count($content);$i++){
    switch($content[$i]){
    case '0': echo "This is nobody<br>";break;
    case "1": echo "This is one people<br>";break;
    case "2": echo "This is two people<br>";break;
    case "3": echo "This is three people<br>";break;
    case "4": echo "This is four people<br>";break;
    case "5": echo "This is five people<br>";break;
    case "6": echo "This is six people<br>";break;
    case "7": echo "This is seven people<br>";break;
    case "8": echo "This is eight people<br>";break;
    case "9": echo "This is nine people<br>";break;
    default:echo "others";
   }
  }
 }
}
 
//封装好的对具体解释器的调用类,非解释器模式必须的角色
class Interpreter{
  private $interpreter;
  private $content;
  function __construct($expression){
  $this->content = $expression->getContent();
  if($this->content[0] == "Chinese"){
    $this->interpreter = new ChineseInterpreter();
   }else{
    $this->interpreter = new EnglishInterpreter();
   }
  }
  function execute(){
   $this->interpreter->interpret($this->content);
  }
}
 
//测试
$expression = new Expression();
$expression->content = array("Chinese",3,2,4,4,5);
$interpreter = new Interpreter($expression);
$interpreter->execute();
 
$expression = new Expression();
$expression->content = array("English",1,2,3,0,0);
$interpreter = new Interpreter($expression);
$interpreter->execute();
?>

结果:

三个人
二个人
四个人
四个人
五个人
This is one people
This is two people
This is three people
This is nobody
This is nobody

好啦,本次记录就到这里了。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》