【设计模式】第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()
	}
}
相关推荐
冷崖11 小时前
工厂模式-创建型
c++·设计模式
何中应15 小时前
【面试题-5】设计模式
java·开发语言·后端·设计模式·面试题
沐森19 小时前
在实战中运用泛型和动态trait(特质)
设计模式
lomocode20 小时前
改一个需求动 23 处代码?你可能踩进了这个坑
后端·设计模式
喷火龙8号20 小时前
JWT 认证方案深度对比:单 Token 扩展刷新 vs 双 Token 验证
后端·设计模式·架构
fakerth2 天前
【OpenHarmony】设计模式模块详解
c++·单例模式·设计模式·openharmony
alibli2 天前
一文学会设计模式之创建型模式及最佳实现
c++·设计模式
1024肥宅2 天前
前端常用模式:提升代码质量的四大核心模式
前端·javascript·设计模式
郝学胜-神的一滴2 天前
设计模式依赖于多态特性
java·开发语言·c++·python·程序人生·设计模式·软件工程
帅次2 天前
系统分析师:软件需求工程的软件需求概述、需求获取、需求分析
设计模式·重构·软件工程·团队开发·软件构建·需求分析·规格说明书