【设计模式】第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()
	}
}
相关推荐
诙_3 小时前
深入理解C++设计模式
c++·设计模式
AI大法师5 小时前
从门头到社媒预热图,快闪项目如何统一视觉输出
大数据·人工智能·设计模式
Pkmer7 小时前
类的封装性: 让门面设计模式来打开这扇门
后端·设计模式
Pkmer7 小时前
古法编程: 我要的是状态模式,策略模式不要误我大计
后端·设计模式
雪度娃娃8 小时前
创建型设计模式——建造者模式
c++·microsoft·设计模式·建造者模式
老衲提灯找美女8 小时前
多线程(2)-设计模式:单列模式
设计模式
Dabei1 天前
Android 无障碍服务实现美团/微信自动化:客户端开发实践
前端·设计模式
巴沟旮旯儿1 天前
vite项目配置文件和打包
前端·设计模式
雪度娃娃1 天前
设计模式——单例模式
开发语言·c++·设计模式
逝水如流年轻往返染尘1 天前
设计模式之单例模式
单例模式·设计模式