• 设计模式_解释器模式


    解释器模式 

    案例

    角色

    1 解释器基类                 (BaseInterpreter)

    2 具体解释器1 2 3...        (Interperter 1 2 3 )

    3 内容                              (Context)

    4 用户                              (user)

           

      流程

    (上下文) ---- 传给排好顺序的解释器(可以通过配置文件信息排序)

                  ---- 得到(修改后的上下文) 

    代码

    角色 Context

    1. // 内容
    2. public class Context
    3. {
    4. private string text = null;
    5. public Context(string text)
    6. {
    7. this.text = text;
    8. }
    9. public void Set(string newText)
    10. {
    11. text = newText;
    12. }
    13. public string Get()
    14. {
    15. return text;
    16. }
    17. }

    角色 BaseInterpreter

    1. // 解释器基类
    2. public abstract class BaseInterpreter
    3. {
    4. public abstract void Conversion(Context context);
    5. }

    角色 Interpreter1

    1. public class Interpreter1 : BaseInterpreter
    2. {
    3. public override void Conversion(Context context)
    4. {
    5. // 1 改为 A
    6. string text = context.Get();
    7. char[] c = text.ToCharArray();
    8. for (int i = 0; i < c.Length; i++)
    9. {
    10. if (c[i] == '1')
    11. {
    12. c[i] = 'A';
    13. }
    14. }
    15. context.Set(new string(c));
    16. }
    17. }

    角色 Interpreter2

            和1类似 仅仅 2=B

    角色 Interpreter3 

            和1类似 仅仅 3=C

    角色 用户

    1. using System.Collections.Generic;
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. public class Player : MonoBehaviour
    5. {
    6. // 显示出内容
    7. public GameObject obj = null;
    8. void Start()
    9. {
    10. // 上下文
    11. Context context = new Context("123456789");
    12. // 创建解码
    13. List interpreterList = new List();
    14. interpreterList.Add(new Interpreter1());
    15. interpreterList.Add(new Interpreter2());
    16. interpreterList.Add(new Interpreter3());
    17. // 开始解码
    18. foreach (var item in interpreterList)
    19. {
    20. item.Conversion(context);
    21. }
    22. obj.GetComponent().text = context.Get();
    23. }
    24. }

    运行结果

  • 相关阅读:
    MySQL 索引
    SpringCloud Gateway搭建Gateway 微服务应用实例
    Springboot 中使用elasticsearch
    深入浅出Python正则表达式:原理与应用
    【链表】合并k个已排序的链表
    软件架构师
    Apache Doris的Bucket Shuffle Join实现
    基于JavaWeb的果蔬生鲜交易系统
    Android实现动态换肤-原理篇
    CentOS 7启动时报“Started Crash recovery kernel arming.....shutdown....”问题处理过程
  • 原文地址:https://blog.csdn.net/qq_30926011/article/details/133090447