1.特色:若某特定問題發生的頻率足夠高時考慮,需定義文法表示與解釋器自己。html
2.概念:在軟件開發特別是DSL開發中經常須要使用一些相對較複雜的業務語言,若是業務語言使用頻率足夠高,且使用普通的編程模式來實現會致使很是複雜的變化,那麼就能夠考慮使用解釋器模式構建一個解釋器對複雜的業務語言進行翻譯。這種作法雖然效率相對較低,但能夠容許用戶使用自定義的業務語言來處理邏輯,所以在效率不是關鍵問題的場合仍是較爲有用的。express
3.類圖:編程
4.程序實現:app
public static class ChineseEnglishDict { private static Dictionary<string, string> _dictory = new Dictionary<string, string>(); static ChineseEnglishDict() { _dictory.Add("this", "這"); _dictory.Add("is", "是"); _dictory.Add("an", "一個"); _dictory.Add("apple", "蘋果"); } public static string GetEnglish(string value) { return _dictory[value]; } } public interface IExpression { void Interpret(StringBuilder sb); } public class WordExpression : IExpression { private string _value; public WordExpression(string value) { _value = value; } public void Interpret(StringBuilder sb) { sb.Append(ChineseEnglishDict.GetEnglish(_value.ToLower())); } } public class SymbolExpression : IExpression { private string _value; public SymbolExpression(string value) { _value = value; } public void Interpret(StringBuilder sb) { switch (_value) { case "." : sb.Append("。"); break; } } } public static class Translator { public static string Translate(string sentense) { StringBuilder sb = new StringBuilder(); List<IExpression> expressions = new List<IExpression>(); string [] elements = sentense.Split(new char [] {'.'}, StringSplitOptions.RemoveEmptyEntries); foreach (string element in elements) { string[] words = element.Split(new char [] {' '}, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { expressions.Add(new WordExpression(word)); } expressions.Add(new SymbolExpression(".")); } foreach (IExpression expression in expressions) { expression.Interpret(sb); } return sb.ToString(); } } static void Main(string[] args) { string englist = "This is an apple."; string chinese = Translator.Translate(englist); Console.WriteLine(chinese); }
http://www.cnblogs.com/saville/p/3379533.htmlui