Unity 解释器模式(实例详解)

文章目录

在Unity中,解释器模式(Interpreter Pattern)并不像命令模式那样常见,因为Unity主要用于游戏开发,其中对脚本语言的解释执行通常由引擎内部完成。然而,解释器模式适用于设计和实现一种特定语法或表达式的解释系统,例如自定义逻辑规则、配置文件解析等。

解释器模式包含以下组件:

  1. 抽象表达式(Abstract Expression)
  2. 终结符表达式(Terminal Expression)
  3. 非终结符表达式(Non-terminal Expression)
  4. 环境角色(Context)

由于Unity项目中直接使用解释器模式的例子相对较少,我们可以构造一个简化的场景来演示其概念:

示例1:基础解释器结构

csharp 复制代码
// 抽象表达式接口
public interface IExpression
{
    bool Interpret(Context context);
}

// 终结符表达式 - 例如检查某个变量是否大于5
public class GreaterThanFive : IExpression
{
    private string _variableName;

    public GreaterThanFive(string variableName)
    {
        _variableName = variableName;
    }

    public bool Interpret(Context context)
    {
        int value = context.GetVariable(_variableName);
        return value > 5;
    }
}

// 非终结符表达式 - 例如逻辑与操作
public class AndExpression : IExpression
{
    private IExpression _left, _right;

    public AndExpression(IExpression left, IExpression right)
    {
        _left = left;
        _right = right;
    }

    public bool Interpret(Context context)
    {
        return _left.Interpret(context) && _right.Interpret(context);
    }
}

// 环境角色 - 提供上下文数据
public class Context
{
    private Dictionary<string, int> _variables;

    public Context()
    {
        _variables = new Dictionary<string, int>();
    }

    public void SetVariable(string name, int value)
    {
        _variables[name] = value;
    }

    public int GetVariable(string name)
    {
        if (_variables.ContainsKey(name))
            return _variables[name];
        else
            throw new KeyNotFoundException($"Variable {name} not found.");
    }
}

// 使用示例
var context = new Context();
context.SetVariable("score", 7);

var isScoreGreaterThanFive = new GreaterThanFive("score");
var hasPowerUp = new GreaterThanFive("powerUpsCollected");

var andExpression = new AndExpression(isScoreGreaterThanFive, hasPowerUp);
bool result = andExpression.Interpret(context); // 返回true,因为score > 5且powerUpsCollected > 5(假设已设置)

当然,以下是示例2至5的详细代码实现:

示例2:小于表达式(LessThanExpression)

csharp 复制代码
public class LessThanExpression : IExpression
{
    private string _variableName;
    private int _threshold;

    public LessThanExpression(string variableName, int threshold)
    {
        _variableName = variableName;
        _threshold = threshold;
    }

    public bool Interpret(Context context)
    {
        int value = context.GetVariable(_variableName);
        return value < _threshold;
    }
}

// 使用:
var lessThanExpression = new LessThanExpression("health", 30);
context.SetVariable("health", 25);
bool isHealthLow = lessThanExpression.Interpret(context); // 返回true,因为health < 30

示例3:逻辑或表达式(OrExpression)

csharp 复制代码
public class OrExpression : IExpression
{
    private IExpression _left, _right;

    public OrExpression(IExpression left, IExpression right)
    {
        _left = left;
        _right = right;
    }

    public bool Interpret(Context context)
    {
        return _left.Interpret(context) || _right.Interpret(context);
    }
}

// 使用:
var hasScoreGreaterThanFive = new GreaterThanFive("score");
var hasHealthGreaterThanZero = new LessThanExpression("health", 0).Inverse();

var orExpression = new OrExpression(hasScoreGreaterThanFive, hasHealthGreaterThanZero);
bool result = orExpression.Interpret(context); // 返回true,只要score > 5 或 health <= 0 其中一个条件满足

示例4:逻辑非表达式(NotExpression)

为了创建逻辑非表达式,我们首先需要为IExpression接口添加一个辅助方法Inverse()以反转其结果。

csharp 复制代码
public interface IExpression
{
    bool Interpret(Context context);
    IExpression Inverse();
}

public abstract class BaseExpression : IExpression
{
    public abstract bool Interpret(Context context);

    public IExpression Inverse()
    {
        return new NotExpression(this);
    }
}

public class NotExpression : IExpression
{
    private IExpression _innerExpression;

    public NotExpression(IExpression innerExpression)
    {
        _innerExpression = innerExpression;
    }

    public bool Interpret(Context context)
    {
        return !_innerExpression.Interpret(context);
    }

    public IExpression Inverse()
    {
        return _innerExpression; // 反转两次等于原表达式
    }
}

// 使用:
var notExpression = new GreaterThanFive("score").Inverse();
bool isScoreNotGreaterThanFive = notExpression.Interpret(context); // 返回true,当score <= 5时

示例5:等于表达式(EqualToExpression)

csharp 复制代码
public class EqualToExpression : IExpression
{
    private string _variableName;
    private int _value;

    public EqualToExpression(string variableName, int value)
    {
        _variableName = variableName;
        _value = value;
    }

    public bool Interpret(Context context)
    {
        int value = context.GetVariable(_variableName);
        return value == _value;
    }
}

// 使用:
var equalToExpression = new EqualToExpression("level", 10);
context.SetVariable("level", 10);
bool isLevelTen = equalToExpression.Interpret(context); // 返回true,因为level == 10

以上就是对解释器模式中的更多复杂表达式的实现。每个表达式都是上下文环境的一部分,并且可以被组合和嵌套来构建更复杂的逻辑结构。

python推荐学习汇总连接:
50个开发必备的Python经典脚本(1-10)

50个开发必备的Python经典脚本(11-20)

50个开发必备的Python经典脚本(21-30)

50个开发必备的Python经典脚本(31-40)

50个开发必备的Python经典脚本(41-50)


​最后我们放松一下眼睛

相关推荐
EQ-雪梨蛋花汤1 小时前
【Unity笔记】Unity Lighting Settings 全解析:一文读懂烘焙光照的每个参数(VR项目Lighting优化)
笔记·unity·vr
WangMing_X2 小时前
《使用模块化分层来达到企业级项目要求》
开发语言·c#
c#上位机5 小时前
wpf之ToggleButton控件
c#·wpf
mit6.82414 小时前
[C# starter-kit] 命令/查询职责分离CQRS | MediatR |
java·数据库·c#
beyond谚语17 小时前
C#学习小笔记(完整版)—— Patience
c#
爱吃小胖橘17 小时前
Unity网络开发--超文本传输协议Http(1)
开发语言·网络·网络协议·http·c#·游戏引擎
IT小农工18 小时前
Word 为每一页设置不同页边距(VBA 宏)
开发语言·c#·word
sali-tec18 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
BrightMZM20 小时前
记录一下Unity的BUG,Trial Version
unity·bug·打包·trial
咕白m62520 小时前
C# 合并多个PDF文档:高效解决方案
c#·.net