《大话设计模式》解释器模式-音符场景-PHP版代码

Standard

解释器模式
音符场景

<?php
/**
 * 解释器模式 音符场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
class PlayContext{
	private $PlayText;
 
        public function __get($property_name){
                if(isset($this->$property_name)){
                        return($this->$property_name);
                }else{
                        return(NULL);
                }
        }
        public function __set($property_name, $value){
                $this->$property_name = $value;
        }
 
}
 
abstract class Expression{
	public function Interpret(PlayContext $context){
		if( strlen($context->PlayText)==0 ){
			return;
		}else{
			$PlayKey = substr($context->PlayText, 0, 1);
			$context->PlayText = substr($context->PlayText, 2);
			$PlayValue = substr( $context->PlayText, 0, strpos($context->PlayText, ' ') );
			$context->PlayText = substr($context->PlayText, strpos($context->PlayText, ' ') + 1 );
 
			$this->Excute($PlayKey, $PlayValue);
		}
	}
	public abstract function Excute($key, $value);
}
 
//音符类
class Note extends Expression{
	public function Excute($key, $value){
		$note = "";
		switch($key){
		case "C":
			$note = "1";
			break;
		case "D":
			$note = "2";
			break;
		case "E":
			$note = "3";
			break;
		case "F":
			$note = "4";
			break;
		case "G":
			$note = "5";
			break;
		case "A":
			$note = "6";
			break;
		case "B":
			$note = "7";
			break;
		}
		echo $note . " ";
	}
}
//音阶类
class Scale extends Expression{
	public function Excute($key, $value){
		$scale = "";
		switch($value){
		case "1":
			$scale = "低音";
			break;
		case "2":
			$scale = "中音";
			break;
		case "3":
			$scale = "高音";
			break;
		}
		echo $scale . " ";
	}
}
//速度类
class Speed extends Expression{
	public function Excute($key, $value){
		$speed = "";
		if ( $value < 500 ) 
			$speed = "快速";
		elseif( $value >= 1000 )
			$speed = "慢速";
		else
			$speed = "中速";
 
		echo $speed . " ";
	}
}
 
class Main{
	public static function run(){
		$context = new PlayContext();
		$context->PlayText = "T 500 O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3";
		try{
			while ( strlen($context->PlayText) > 0 ){
				$str = substr($context->PlayText, 0, 1);
				switch($str){
				case "O":
					$expression = new Scale();
					break;
				case "T":
					$expression = new Speed();
					break;
				default:
					$expression = new Note();
					break;
				}
				$expression->Interpret($context);
			}
 
		} catch (Exception $e) {
			echo $e;
		}
	}
}
Main::run();
?>
//php Expression.php 
//中速 中音 3 5 6 3 5 2 3 5 6 高音 1 中音 6 5 1 3 2

转载请注明出处 http://yemaosheng.com

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.