php 解释器模式,C#设计模式:解释器模式(Interpreter Pattern)

本文介绍了解释器模式在处理业务规则变化频繁且模式重复的场景中的应用。通过一个示例展示了如何使用解释器模式解释和转换特定语言,如中国人和美国人对特定词汇的不同解释方式,强调了解释器模式适用于简单的语言文法和执行效率不是首要关注点的情况。
摘要由CSDN通过智能技术生成

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespace_23.解释器模式

{///

///Interpreter模式的应用场合是Interpreter模式应用中的难点,只有满足“业务规则频繁变化,且类似的模式不断重复出现,并且容易抽象为语法规则的问题”才适合使用Interpreter模式。///1、当一个语言需要解释执行,并可以将该语言中的句子表示为一个抽象语法树的时候,可以考虑使用解释器模式(如XML文档解释、正则表达式等领域)///2、一些重复出现的问题可以用一种简单的语言来进行表达。///3、一个语言的文法较为简单.///4、当执行效率不是关键和主要关心的问题时可考虑解释器模式(注:高效的解释器通常不是通过直接解释抽象语法树来实现的,而是需要将它们转换成其他形式,使用解释器模式的执行效率并不高。)///

classProgram

{static void Main(string[] args)

{

Context context= new Context("usachi");

List interpreterList = new List()

{newChinese(),newUsa(),

};foreach (var item ininterpreterList)

{

item.Conversion(context);

}

Console.WriteLine(context.Get());

}

}///

///上下文///

public classContext

{private string _Word = null;public Context(stringword)

{this._Word =word;

}public void Set(stringnewWord)

{this._Word =newWord;

}public stringGet()

{return this._Word;

}

}///

///抽象解释器///

public abstract classPeopleInterpreter

{public abstract voidConversion(Context context);

}///

///中国人业务///

public classChinese : PeopleInterpreter

{private static Dictionary _Dictionary = new Dictionary();///

///中国人自己解释规则///

staticChinese()

{

_Dictionary.Add('u', "美国人");

_Dictionary.Add('s', "用刀叉");

_Dictionary.Add('a', "吃饭,");

}public override voidConversion(Context context)

{

Console.WriteLine(this.GetType().ToString() + "业务");string text =context.Get();if (string.IsNullOrEmpty(text))return;

List numberList = new List();foreach (var item intext.ToLower().ToArray())

{if(_Dictionary.ContainsKey(item))

{

numberList.Add(_Dictionary[item]);

}else{

numberList.Add(item.ToString());

}

}

context.Set(string.Concat(numberList));

}

}///

///美国人业务///

public classUsa : PeopleInterpreter

{private static Dictionary _Dictionary = new Dictionary();///

///美国人自己解释规则///

staticUsa()

{

_Dictionary.Add('c', "中国人");

_Dictionary.Add('h', "用");

_Dictionary.Add('i', "筷子吃饭");

}public override voidConversion(Context context)

{

Console.WriteLine(this.GetType().ToString() + "业务");string text =context.Get();if (string.IsNullOrEmpty(text))return;

List numberList = new List();foreach (var item intext.ToLower().ToArray())

{if(_Dictionary.ContainsKey(item))

{

numberList.Add(_Dictionary[item]);

}else{

numberList.Add(item.ToString());

}

}

context.Set(string.Concat(numberList));

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值