【设计模式】第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()
	}
}
相关推荐
漫谈网络1 分钟前
MVC与MVP设计模式对比详解
设计模式·mvc
蔡蓝8 分钟前
设计模式-观察着模式
java·开发语言·设计模式
哆啦A梦的口袋呀2 小时前
基于Python学习《Head First设计模式》第六章 命令模式
python·学习·设计模式
半路下车3 小时前
【Harmony OS 5】HarmonyOS应用测试指南
设计模式·harmonyos
周某某~3 小时前
一.设计模式的基本概念
设计模式
on the way 1234 小时前
行为型设计模式之Interpreter(解释器)
设计模式
cui_hao_nan4 小时前
设计模式——模板方法
java·设计模式
在未来等你4 小时前
Java并发编程实战 Day 11:并发设计模式
java·设计模式·多线程·并发编程·threadlocal·生产者消费者·读写锁
牛奶咖啡135 小时前
学习设计模式《十二》——命令模式
学习·设计模式·命令模式·队列请求·宏命令·可撤销恢复操作·参数化配置
哆啦A梦的口袋呀6 小时前
基于Python学习《Head First设计模式》第七章 适配器和外观模式
python·学习·设计模式