标签:简单的 就会 ice highlight 替换 int ext html模板 array
用于分析一个实体的关键元素,并且针对每个元素都提供自己的解释或相应的动作.
这个模式应该是我们较为常用的,php/html模板系统中就会用到.
class A
{
public function getInfo()
{
return ‘{{B.info}} or {{B.info}}‘;
}
}
class B
{
public function info()
{
return ‘this is info from B‘;
}
}
class Interpreter
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function execute()
{
$userInfo = $this->a->getInfo();
if (preg_match_all(‘/\{\{B\.(.*?)\}\}/‘, $userInfo, $arr, PREG_SET_ORDER)) {
$replace = array();
foreach ($arr as $val) {
$replace[] = $val[1];
}
$replace = array_unique($replace);
$b = new B();
foreach ($replace as $rep) {
$userInfo = str_replace("{{B.{$rep}}}", call_user_func(array($b, $rep)), $userInfo);
}
}
return $userInfo;
}
}
// 调用
$a = new A();
$interpreter = new Interpreter($a);
echo $interpreter->execute();
在Interpreter类中初始化时创建了A的实例,其实也可以用继承来实现.
特点:
用于分析实体的关键元素,也就是说元素需要创建类的实例之后才是明确的.这点也是肯定的,否则,就没有解释器模式存在了.
需要预先知道大致对元素做何种解释.知道就可以switch/case.否则就是一个简单的if/else.如上例,我们就知道要替换B.info为对应内容.
模板设计模式创建了一个实施一组方法和功能的抽象对象,子类通常将这个对象作为模板用于自己的设计.
所有的商品类在用户购买前,都需要给用户显示出最终支付的费用.但有些商品需要纳税,有些商品可能有打折.
abstract class Product
{
protected $payPrice = 0;
public final function setAdjustment()
{
$this->payPrice += $this->discount();
$this->payPrice += $this->tax();
}
public function getPayPrice()
{
return $this->payPrice;
}
protected function discount()
{
return 0;
}
abstract protected function tax();
}
class CD extends Product
{
public function __construct($price)
{
$this->payPrice = $price;
}
protected function tax()
{
return 0;
}
}
class IPhone extends Product
{
public function __construct($price)
{
$this->payPrice = $price;
}
protected function tax()
{
return $this->payPrice * 0.2;
}
protected function discount()
{
return -10;
}
}
$cd = new CD(15);
$cd->setAdjustment();
echo $cd->getPayPrice();
$iphone = new IPhone(6000);
$iphone->setAdjustment();
echo $iphone->getPayPrice();
标签:简单的 就会 ice highlight 替换 int ext html模板 array
原文地址:http://www.cnblogs.com/itfenqing/p/7750604.html