您的位置:首页 > 编程语言 > C#

C#设计模式——解释器模式

2016-12-05 11:02 204 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Explaining
{
public class Translaton
{
public static string Translator(string source)
{
StringBuilder StringBuilder = new StringBuilder();//新建一个可变字符串对象
List<ITarget> TranslationList = new List<ITarget>();//新建一个存放翻译的列表
string[] words1 = source.Split(new char []{'.'},StringSplitOptions.RemoveEmptyEntries);//拆分输入的字符串的单词和符号
foreach (string wd1 in words1)
{
string[] word2 = wd1.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries);//拆分单词,通过空格空格
foreach (string wd2 in word2)
{
TranslationList.Add(new Expression(wd2));
}
TranslationList.Add(new smybols("."));
}
foreach (ITarget sy in TranslationList)
{
sy.interpret(StringBuilder);//
}
return StringBuilder.ToString();
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Explaining
{
public class EnglishToChinese
{
static Dictionary<string, string> WordsDictionary = new Dictionary<string, string>();//定义英汉翻译内容
static EnglishToChinese()
{
WordsDictionary.Add("this","这");
WordsDictionary.Add("is", "是");
WordsDictionary.Add("a", "一部");
WordsDictionary.Add("huawei", "华为");
WordsDictionary.Add("phone", "手机");
}
public static string  GetChinese(string english)//定义英汉翻译方法
{
return WordsDictionary[english];//使用索引通过key查询Value
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Explaining
{
public interface ITarget
{
void interpret(StringBuilder StringBuilder);//定义接口
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Explaining
{
public class Expression:ITarget
{
private string english;
public Expression(string eg )//封装构造
{
this.english = eg;
}
public void interpret(StringBuilder StringBiulder)
{
StringBiulder.Append(EnglishToChinese.GetChinese(english.ToLower()));//获取word中的英语key并转为小写,通过索引转为汉语,添加至stringbuilder中
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Explaining
{
class Program
{
static void Main(string[] args)
{
string ss = "this is a huawei phone.";
string print = Translaton.Translator(ss);//传入参数
Console.WriteLine(print);
//Console.Read();
Console.ReadKey();

}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Explaining
{
public class smybols:ITarget
{
private string smybol;
public smybols(string symbol)
{

4000
this.smybol = symbol;
}
public void interpret(StringBuilder StringBuilder)//定义英汉标点的翻译方法
{
switch (smybol)
{
case".":
StringBuilder.Append("。");
break;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息