场景:大小写数字互相转换

abstract class Expresstion { //解释器 public void Interpret(PlayContext context) { string value = context.PlayText.Substring(0,1); Translate(value);//处理当前字符 context.PlayText = context.PlayText.Substring(1); //去除已处理的字符 } public abstract void Translate(string key); } class Upper : Expresstion { public override void Translate(string key) { string upper = ""; switch (key) { case "1":upper = "一";break; case "2": upper = "二"; break; case "3": upper = "三"; break; case "4": upper = "四"; break; case "5": upper = "五"; break; case "6": upper = "六"; break; case "7": upper = "七"; break; case "8": upper = "八"; break; case "9": upper = "九"; break; case "0": upper = "零"; break; } Console.Write(upper); } } class Lower : Expresstion { public override void Translate(string key) { string lower = ""; switch (key) { case "一": lower = "1"; break; case "二": lower = "2"; break; case "三": lower = "3"; break; case "四": lower = "4"; break; case "五": lower = "5"; break; case "六": lower = "6"; break; case "七": lower = "7"; break; case "八": lower = "8"; break; case "九": lower = "9"; break; case "零": lower = "0"; break; } Console.Write(lower); } } //上下文 class PlayContext { private string playText; public string PlayText { get { return playText; } set { playText = value; if (value.Length > 0) { Expresstion expresstion = null; string values = playText.Substring(0, 1); switch (values) { case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "0": expresstion = new Upper(); break; case "一": case "二": case "三": case "四": case "五": case "六": case "七": case "八": case "九": case "零": expresstion = new Lower(); break; } expresstion.Interpret(this); } } } } //前端 static void Main(string[] args) { PlayContext playContext = new PlayContext(); playContext.PlayText = "123四五六7八9零"; Console.ReadLine(); }

总结:设定规则将当前语法转变成另外一种语言。当一个语言需要解释执行,并且可将该语言中的句子表示为抽象语法树的时候,可使用该模式。
好处:容易扩展文法规则,并且各个节点的规则类很容易编写。
缺点:用了递归,效率要差、使用场景不多、规则多的时候难维护。