解释器模式

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();
        }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值