zoukankan      html  css  js  c++  java
  • php设计模式之解释器模式

    解释器设计模式用于分析一个实体的关键元素,并且针对每个元素都提供自己的解释或相应的动作。

    <?php
    /**
    * 解释器模式
    */
    class User
    {
        protected $_username;
    
        public function __construct($username)
        {
            $this->_username = $username;
        }
    
        public function getProfilePage()
        {
            $profile = "<h2>I like never again</h2>";
            $profile .= "I love all of the songs, My favorite CD:<br/>";
            $profile .= "{{myCD.getTitle}}<br/>";
            $profile .= "My name is ";
            $profile .= "{{myCD.getName}}";
    
            return $profile;
        }
    }
    
    /**
    *ad
    */
    class userCD
    {
        protected $_user = NULL;
        public function setUser($user)
        {
            $this->_user = $user;
        }
    
        public function getTitle()
        {
            return 'test';
        }
    
        public function getName()
        {
            return '111';
        }
    }
    /**
    * interpreter
    */
    class userCDInterpreter
    {
        protected $_user = NULL;
        function setUser($user)
        {
            $this->_user = $user;
        }
    
        public function getInterpreted()
        {
            $profile = $this->_user->getProfilePage();
            if (preg_match_all('/{{myCD.(.*?)}}/', $profile, $triggers, PREG_SET_ORDER)) {
                $replacements = array();
    
                foreach ($triggers as $trigger) {
                    $replacements[] = $trigger[1];
                }
                $replacements = array_unique($replacements);
    
                $myCD = new userCD();
                $myCD->setUser($this->_user);
    
                foreach ($replacements as $replacement) {
                    $profile = str_replace("{{myCD.{$replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
                }
            }
            
            return $profile;
        }
    }
    $username = 'aaron';
    $user = new User($username);
    $interpreter = new userCDInterpreter();
    $interpreter->setUser($user);
    $echo = $interpreter->getInterpreted();
    
    
    print "<h1>{$username}'s Profile</h1>";
    
    print $echo;
  • 相关阅读:
    return false 和 return true
    前端异常采集
    Performance — 前端性能监控利器
    正则笔记-忘记就来看
    JS中的正则应用
    iconfont的使用
    canvas笔记1
    树莓派3B安装DeBian 64位系统及其安装私有云网盘----可道云
    台灯改造【智能台灯】
    单片机C语言中标志位的经典应用
  • 原文地址:https://www.cnblogs.com/happig/p/5399707.html
Copyright © 2011-2022 走看看