解释器模式
案例
角色
1 解释器基类 (BaseInterpreter)
2 具体解释器1 2 3... (Interperter 1 2 3 )
3 内容 (Context)
4 用户 (user)
流程
(上下文) ---- 传给排好顺序的解释器(可以通过配置文件信息排序)
---- 得到(修改后的上下文)
代码
角色 Context
// 内容
public class Context
{
private string text = null;
public Context(string text)
{
this.text = text;
}
public void Set(string newText)
{
text = newText;
}
public string Get()
{
return text;
}
}
角色 BaseInterpreter
// 解释器基类
public abstract class BaseInterpreter
{
public abstract void Conversion(Context context);
}
角色 Interpreter1
public class Interpreter1 : BaseInterpreter
{
public override void Conversion(Context context)
{
// 1 改为 A
string text = context.Get();
char[] c = text.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == '1')
{
c[i] = 'A';
}
}
context.Set(new string(c));
}
}
角色 Interpreter2
和1类似 仅仅 2=B
角色 Interpreter3
和1类似 仅仅 3=C
角色 用户
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
// 显示出内容
public GameObject obj = null;
void Start()
{
// 上下文
Context context = new Context("123456789");
// 创建解码
List<BaseInterpreter> interpreterList = new List<BaseInterpreter>();
interpreterList.Add(new Interpreter1());
interpreterList.Add(new Interpreter2());
interpreterList.Add(new Interpreter3());
// 开始解码
foreach (var item in interpreterList)
{
item.Conversion(context);
}
obj.GetComponent<Text>().text = context.Get();
}
}