解释器模式(Interpreter)
解释器模式,给定一个语言。定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
代码
代码如下:
表达式类
using System;
namespace Interpreter
{
//表达式类(AbstractExpression)
public abstract class Expression
{
//解释器
public void Interpret(PlayContext context){
if (context.playText.Length == 0) {
return;
} else {
string playKey = context.playText.Substring (0, 1);
context.playText = context.playText.Substring (2);
double playValue = Convert.ToDouble (context.playText.Substring (0, context.playText.IndexOf (" ")));
context.playText = context.playText.Substring (context.playText.IndexOf (" ") + 1);
Excute (playKey, playValue);
}
}
//执行
public abstract void Excute(string key,double value);
}
}
音符类
using System;
namespace Interpreter
{
//音符类(TerminalExpression)
public class Note:Expression
{
public override void Excute (string key, double value)
{
string 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;
}
Console.Write ("{0} ", note);
}
}
}
音符类
using System;
namespace Interpreter
{
//音符类(TerminalExpression)
public class Scale:Expression
{
string scale="";
public override void Excute (string key, double value)
{
switch (Convert.ToInt32 (value)) {
case 1:
scale = "低音";
break;
case 2:
scale = "中音";
break;
case 3:
scale = "高音";
break;
}
Console.Write ("{0} ", scale);
}
}
}
演奏内容
using System;
namespace Interpreter
{
//演奏内容(Context)
public class PlayContext
{
//演奏文本
public string playText;
}
}
2.客户端代码如下:
客户端
using System;
namespace Interpreter
{
class MainClass
{
public static void Main (string[] args)
{
PlayContext context = new PlayContext ();
//音乐
Console.WriteLine("上海滩:");
context.playText = "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 ";
Expression expression = null;
try{
while(context.playText.Length>0){
string str=context.playText.Substring(0,1);
switch(str){
case "O":
expression=new Scale();
break;
case "C":
case "D":
case "E":
case "F":
case "G":
case "A":
case "B":
case "P":
expression=new Note();
break;
default:expression=new Note();
break;
}
expression.Interpret(context);
}
}catch(Exception ex){
Console.WriteLine (ex.Message);
}
}
}
}
3.运行结果