给定义一个语言,定义它的文法的一种表示,,并定义一个解释器,这是解释器使用该表示解释语言的句子。
解释器能够提供一个接口,该接口可以连接上下文,并且可以将文章用自己编译的语言来解释。
当某件一个经常出现,且发生频率很高,而且内容大致都相同,则可以通过解释器来将内容进行翻译,从而解决问题
通过建立相应的语言来解释原本的问题
构造一种相应的语言,而且需要连接上下文的环境
(1)优点:
可扩展,灵活性好
比较好实现
(2)缺点:
很少利用,难以维护
将音符转化为数字和中文,让不识谱的人也能够看懂:
1,你所要转换的内容:
class Typecontext { private string text; public string PlayText { get { return text; } set { text = value; } } }2,解释器,可以用来连接上下文:
abstract class Expression { public void Interpret(Typecontext 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); }3,各种语言的转换:
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); } } class Scale : Expression { public override void Excute(string key, double value) { string scale = ""; switch (Convert.ToInt32(value)) { case 1: scale = "低音"; break; case 2: scale = "中音"; break; case 3: scale = "高音"; break; } Console.WriteLine("{0}", scale); } }4,客户端代码:
static void Main(string[] args) { Typecontext mu = new Typecontext(); Console.WriteLine("上海滩:"); mu.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 (mu.PlayText.Length > 0) { string str = mu.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; } expression.Interpret(mu); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); }