设计模式(二十三)——解释器模式

解释器模式(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.运行结果

UML图


源码下载地址 :https://gitee.com/ZhaoYongshuang/DesignPattern.git
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值