1.翻译器
namespace CompilerPattern
{
/// <summary>
/// 解释器模式:编译器抽象类
/// 根据编译器的规则,将输入翻译之后输出
/// 每个规则代表为一个类,然而,当规则众多的时候,将会显得不好管理。
/// 但是,当接收一个输入后需要对应的输出编码输出时,比如说加密,
/// 解释正则表达式等,就可以使用解释器模式
///
/// 这东西跟适配器模式有点类似,但是,适配器模式不需要预先知道要适配的规则,
/// 解释器是根据规则去执行解释
/// </summary>
public abstract class ACompiler
{
/// <summary>
/// 翻译文本:
/// 每两个字符代表一个汉字,
/// 每三个字符代表两个汉字,
/// 字符用0,1表示,
/// 字符间用空格隔开
/// </summary>
/// <param name="context"></param>
public void SplitText(string context)
{
string[] str = context.Split(' ');
ExecExpain(str);
}
public abstract void ExecExpain(string[] str);
}
/// <summary>
/// 具体实施翻译
/// </summary>
public class DdigitalCompiler : ACompiler
{
public override void ExecExpain(string[] str)
{
foreach (var tmp in str)
{
if (tmp == "11")
Console.WriteLine("笑");
if (tmp == "10")
Console.WriteLine("熬");
if (tmp == "01")
Console.WriteLine("江");
if (tmp == "00")
Console.WriteLine("湖");
}
}
}
/// <summary>
/// 具体实施翻译
/// </summary>
public class DdigitalCompilerEx : ACompiler
{
public override void ExecExpain(string[] str)
{
foreach (var tmp in str)
{
if (tmp == "111")
Console.WriteLine("东方");
if (tmp == "100")
Console.WriteLine("不败");
if (tmp == "011")
Console.WriteLine("江湖");
if (tmp == "001")
Console.WriteLine("郎中");
}
}
}
}
2.调用
static void Main(string[] args)
{
string context = "11 10 01 00 111 100 011 001";
ACompiler aACompiler = null;
string str = context.Substring(0, 11);
aACompiler = new DdigitalCompiler();
aACompiler.SplitText(str);
aACompiler =new DdigitalCompilerEx();
aACompiler.SplitText(context.Remove(0, str.Length));
Console.ReadKey();
}