php设计模式 Interpreter(解释器模式)
程序员文章站
2023-02-26 15:48:41
复制代码 代码如下:
<?php
/**
* 解释器 示例
*
* @create_date: 2010-01-04
*/
class expression
{
function interpreter($str)
{
return $str;
}
}
class expressionnum extends expression
{
function interpreter($str)
{
switch($str)
{
case "0": return "零";
case "1": return "一";
case "2": return "二";
case "3": return "三";
case "4": return "四";
case "5": return "五";
case "6": return "六";
case "7": return "七";
case "8": return "八";
case "9": return "九";
}
}
}
class expressioncharater extends expression
{
function interpreter($str)
{
return strtoupper($str);
}
}
class interpreter
{
function execute($string)
{
$expression = null;
for($i = 0;$i<strlen($string);$i++) {
$temp = $string[$i];
switch(true)
{
case is_numeric($temp): $expression = new expressionnum(); break;
default: $expression = new expressioncharater();
}
echo $expression->interpreter($temp);
}
}
}
$obj = new interpreter();
$obj->execute("12345abc");
?>
复制代码 代码如下:
<?php
/**
* 解释器 示例
*
* @create_date: 2010-01-04
*/
class expression
{
function interpreter($str)
{
return $str;
}
}
class expressionnum extends expression
{
function interpreter($str)
{
switch($str)
{
case "0": return "零";
case "1": return "一";
case "2": return "二";
case "3": return "三";
case "4": return "四";
case "5": return "五";
case "6": return "六";
case "7": return "七";
case "8": return "八";
case "9": return "九";
}
}
}
class expressioncharater extends expression
{
function interpreter($str)
{
return strtoupper($str);
}
}
class interpreter
{
function execute($string)
{
$expression = null;
for($i = 0;$i<strlen($string);$i++) {
$temp = $string[$i];
switch(true)
{
case is_numeric($temp): $expression = new expressionnum(); break;
default: $expression = new expressioncharater();
}
echo $expression->interpreter($temp);
}
}
}
$obj = new interpreter();
$obj->execute("12345abc");
?>
上一篇: 火车上的沉思
下一篇: PHP $_FILES函数详解