• 设计模式_解释器模式


    解释器模式 

    案例

    角色

    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. }

    运行结果

  • 相关阅读:
    静电模型PIC方法的Matlab仿真设计
    (C语言)P1002 [NOIP2002 普及组] 过河卒
    机器学习或者机器视觉代码讲解视频教程
    Linux c++ 中文字符转十六进制 UTF-8 编码
    html 中 title与h1,b与strong,i与em区别?
    技术解读数据库如何实现“多租户”?
    bind命令
    kubernetes kube-apiserver 存在SSRF漏洞
    【基于YOLOv8的教室人脸识别 附源码 数据集】
    如何在mac下使用homebrew安装 mysql?
  • 原文地址:https://blog.csdn.net/qq_30926011/article/details/133090447