【设计模式】第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()
	}
}
相关推荐
周努力.2 小时前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z17 小时前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry18 小时前
常用设计模式
设计模式
z263730561119 小时前
六大设计模式--OCP(开闭原则):构建可扩展软件的基石
设计模式·开闭原则
01空间1 天前
设计模式简述(十八)享元模式
设计模式·享元模式
秋名RG1 天前
深入理解设计模式之原型模式(Prototype Pattern)
设计模式·原型模式
Li小李同学Li2 天前
设计模式【cpp实现版本】
单例模式·设计模式
周努力.2 天前
设计模式之状态模式
设计模式·状态模式
268572592 天前
Java 23种设计模式 - 行为型模式11种
java·开发语言·设计模式
摘星编程2 天前
并发设计模式实战系列(19):监视器(Monitor)
设计模式·并发编程