【设计模式】第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()
	}
}
相关推荐
码匠许师傅19 小时前
【设计模式精讲】15.享元模式(Flyweight)
c++·设计模式·享元模式·uml
事圆则缓19 小时前
Android 常用设计模式速查
android·设计模式
码匠许师傅1 天前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
evans在进步1 天前
Java 常用设计模式(二):装饰器、适配器、责任链、模板方法、策略与观察者
java·开发语言·设计模式
码匠许师傅2 天前
【设计模式精讲】13.装饰器模式(Decorator)
c++·设计模式·uml·装饰器模式
evans在进步3 天前
Java 常用设计模式入门:建造者、工厂、单例、外观与代理
java·python·设计模式
字节跳动开源3 天前
VisActor全新图可视化开源项目:VGraph
前端·设计模式·开源
码匠许师傅3 天前
【设计模式精讲】11.桥接模式(Bridge)
c++·设计模式·桥接模式·uml
学习星球4 天前
AI Agent 成本工程实战:从 OpenAI Codex 的 8 个“烧 Token“Bug 学起
人工智能·设计模式·微信小程序
AI人工智能+电脑小能手4 天前
大白话说Java设计模式-46-责任链模式(业务实战篇)
java·设计模式·责任链模式·风控校验·servlet filter·spring interceptor·链式处理