B11:解释器模式 Iterpreter

给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子.

UML:

示例代码:

abstract class Expression
{
    abstract public function interpreter($body);
}

class InterpreterFace extends Expression
{
    public function interpreter($body)
    {
        return str_replace('[:2]', 'a.gif', $body);
    }

}

class InterpreterJs extends Expression
{
    public function interpreter($body)
    {
        $body = str_replace('<script>', '[script]', $body);
        $body = str_replace('</script>', '[/script]', $body);
        return $body;
    }
}

$str = '[:2] 你好 <script>a.js</script>';

$interpreters = [new InterpreterFace(),new InterpreterJs()];

foreach ($interpreters as $inter) {
    $str = $inter->interpreter($str);
}

echo $str;

  

原文地址:https://www.cnblogs.com/itfenqing/p/7791838.html