解释器模式属于行为设计模式
用来解决原条件不确定,但是有一定规则把原条件按规则执行出来的情况
web开发中,前端通过<%= %> @{} 执行后台代码就是用到了这种设计模式
开发工作中 一般不会用到 理解就好
直接上代码
解释器接口
public interface IExepression
{
char GetWords(char word);
void GetNewText(Context contxt);
}
两个解释器类
public class FirstExepression:IExepression
{
public static Dictionary<char, char> dic = new Dictionary<char, char>();
static FirstExepression()
{
dic.Add('a','啊');
dic.Add('b', '波');
dic.Add('c', '次');
dic.Add('d', '的');
}
public char GetWords(char word)
{
if (dic.ContainsKey(word))
return dic[word];
else
return word;
}
public void GetNewText(Context contxt)
{
char[] chars = contxt.OldText.ToCharArray();
List<char> charList=new List<char>();
foreach (char item in chars)
{
charList.Add(GetWords(item));
}
contxt.OldText = string.Concat(charList);
}
}
public class SecondExepression:IExepression
{
public static Dictionary<char, char> dic = new Dictionary<char, char>();
static SecondExepression()
{
dic.Add('e','额');
dic.Add('f', '佛');
dic.Add('g', '哥');
}
public char GetWords(char word)
{
if (dic.ContainsKey(word))
return dic[word];
else
return word;
}
public void GetNewText(Context contxt)
{
char[] chars = contxt.OldText.ToCharArray();
List<char> charList=new List<char>();
foreach (char item in chars)
{
charList.Add(GetWords(item));
}
contxt.OldText = string.Concat(charList);
}
}
上下文类
public class Context
{
public string OldText { get; set; }
public Context(string txt)
{
OldText = txt;
}
public string NewText()
{
return OldText;
}
}
调用:
//假设需求
//用户传递进来一行字符串
//需要把其中的 abcdefg进行对应的转换然后打印出来
//需求1 abcd 进行对应的转换
//需求2 efg进行对应的转换
//注:就是为了展示两种条件怎么做 故意拆成2种需求 莫纠结
string txt = "absdnsdhbagscahdaejhfs";//模拟用户输入接收后字符串
Context con = new Context(txt);//赋值上下文
List<IExepression> ExeList = new List<IExepression>();
ExeList.Add(new FirstExepression());
ExeList.Add(new SecondExepression());
foreach (IExepression item in ExeList)
{
item.GetNewText(con);
}
Console.WriteLine("成功将{0}转换成为:{1}",txt,con.NewText());
结果: