【设计模式】第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()
	}
}
相关推荐
geovindu13 小时前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh5 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊6 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3336 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx7 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥7 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户624293196628 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊8 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread9 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式
装不满的克莱因瓶9 天前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式