【设计模式】第17节:行为型模式之“解释器模式”

一、简介

解释器模式为某个语言定义它的语法(或者叫文法)表示,并定义一个解释器用来处理这个语法。

二、适用场景

  • 领域特定语言
  • 复杂输入解释
  • 可扩展的语言结构

三、UML类图

四、案例

对输入的特定格式的打印语句进行解析并执行。

go 复制代码
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Expression interface {
	Interpret()
}

type PrintExpression struct {
	Message string
}

func NewPrintExpression(msg string) *PrintExpression {
	return &PrintExpression{Message: msg}
}

func (pe *PrintExpression) Interpret() {
	fmt.Printf("message: %v\n", pe.Message)
}

type RepeatExpression struct {
	RepeatCount int
	Expression  Expression
}

func NewRepeatExpression(repeatCount int, expression Expression) RepeatExpression {
	return RepeatExpression{RepeatCount: repeatCount, Expression: expression}
}

func (re *RepeatExpression) Interpret() {
	for i := 0; i < re.RepeatCount; i++ {
		re.Expression.Interpret()
	}
}

func main() {
	command := "REPEAT 3 TIMES: PRINT Hello"
	words := strings.Split(command, " ")
	fmt.Printf("words: %v\n", words)
	if words[0] == "REPEAT" {
		repeatCount, _ := strconv.Atoi(words[1])
		printExpression := NewPrintExpression(words[4])
		repeatExpression := NewRepeatExpression(repeatCount, printExpression)
		repeatExpression.Interpret()
	}
}
相关推荐
408高手4 小时前
23种设计模式
设计模式
沫璃染墨4 小时前
《Linux工程实践篇(二):线程池实战——从线程安全单例到完整源码实现》
linux·开发语言·c++·单例模式·设计模式·系统架构
sarasuki14 小时前
MCP 为什么是一个协议而不是一个框架呢?
设计模式·agent·mcp
geovindu18 小时前
rust: Borg Pattern(续)
开发语言·后端·设计模式·rust·博格模式
染指11101 天前
140.Agent-多Agent框架-Agent执行Skills流程
数据库·人工智能·设计模式·langchain·agents
sarasuki2 天前
Agent 是怎么做错误处理的呢?
人工智能·设计模式·agent
A1Book2 天前
从 0 设计历史专题资料汇编的 AI Agent 编排架构——六轮真实任务复盘
设计模式
geovindu3 天前
rust: Simple Factory Pattern(续)
后端·设计模式·rust·简单工厂模式·创建型模式
喜欢coding的谢同学3 天前
Go语言常用设计模式基础和实践案例介绍
开发语言·设计模式·golang
sarasuki3 天前
Agent 的记忆有几种?你的名字是?
人工智能·设计模式·agent