解譯器模式分析、結構圖及基本代碼

來源:互聯網
上載者:User

標籤:解譯器模式   Regex   編譯器   擴充   技術   



定義:給定一個語言,定義它的文法的一種表示,並定義一個解譯器,這個解譯器使用該表示來解釋語言中的句子。
適用地:當有一個語言需要解釋執行,並且你可將該語言中的句子表示為一個抽象文法樹時,可使用解譯器模式。如果一種特定類型的問題發生的頻率足夠高,那麼可能就值得將該問題的各個執行個體表述為一個簡單語言中的句子。這樣就可以構建一個解譯器,該解譯器通過解釋這些句子來解決該問題。像Regex、瀏覽器應用等等。
優點是可以很容易地擴充和改變文法,因為該模式使用類來表示文法規則,你可使用繼承來改變或擴充該文法。也比較容易實現文法,因為定義抽象文法樹中各個節點的類的實現大體相似,這些都易於直接編寫。
缺點是解譯器為文法中的每一種規則至少定義了一個類,因此包含許多規則的文法可能難以管理和維護。建議當文法非常複雜時,使用其他的技術如文法剖析器或編譯器產生器來處理。
結構圖:


基本代碼:

using System;
using System.Collections.Generic;
using System.Text;

namespace 解譯器模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context();
            IList<AbstractExpression> list = new List<AbstractExpression>();
            list.Add(new TerminalExpression());
            list.Add(new NonterminalExpression());
            list.Add(new TerminalExpression());
            list.Add(new TerminalExpression());

            foreach (AbstractExpression exp in list)
            {
                exp.Interpret(context);
            }

            Console.Read();
        }
    }

    class Context
    {
        private string input;
        public string Input
        {
            get { return input; }
            set { input = value; }
        }

        private string output;
        public string Output
        {
            get { return output; }
            set { output = value; }
        }
    }

    abstract class AbstractExpression
    {
        public abstract void Interpret(Context context);
    }

    class TerminalExpression : AbstractExpression
    {
        public override void Interpret(Context context)
        {
            Console.WriteLine("終端解譯器");
        }
    }

    class NonterminalExpression : AbstractExpression
    {
        public override void Interpret(Context context)
        {
            Console.WriteLine("非終端解譯器");
        }
    }
}

解譯器模式分析、結構圖及基本代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.