关于C# 设计模式 Interpreter 解释器模式

关于C# 设计模式 Interpreter 解释器模式

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

///Interpreter(解释器)模式描述了如何为简单的语言定义一个文法。
///add by jzh 2007-04-15
namespace DesignPattern
{
    class ContextMi
    {
        private string _statement;
        private string _data;

        public ContextMi(string statement, string data)
        {
            this._statement = statement;
            this._data = data;
        }

        public string Statement
        {
            get { return this._statement; }
            set { this._statement = value; }
        }

        public string Data
        {
            get { return this._data; }
            set { this._data = value; }
        }
    }

    abstract class AbstractExpression
    {
        abstract public void Interpret(ContextMi c);
    }

    class TerminalExpression : AbstractExpression
    {
        override public void Interpret(ContextMi context)
        {
            if (context.Statement.Contains("+"))
            {
                context.Data = context.Statement.Replace("+", ":jzh");
                Console.WriteLine(context.Data);
            }
        }
    }

    class NonterminalExpression : AbstractExpression
    {
        override public void Interpret(ContextMi context)
        {
            if (context.Statement.Contains("-"))
            {
                context.Data = context.Statement.Replace("-", ":9001");
                Console.WriteLine(context.Data);
            }
        }
    }

    public class Client
    {
        public static void Main(string[] args)
        {
            string action = "user+code-";
            string data = "";

            ContextMi c = new ContextMi(action, data);
            ArrayList arr = new ArrayList();

            arr.Add(new TerminalExpression());
            arr.Add(new NonterminalExpression());

            // interpret
            foreach (AbstractExpression exp in arr)
            {
                exp.Interpret(c);
            }

            Console.ReadLine();
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。