建阅读网站,手机百度网页版登录入口,志愿服务网站开发,广州开发区医院南岗院区一、简介
解释器模式为某个语言定义它的语法#xff08;或者叫文法#xff09;表示#xff0c;并定义一个解释器用来处理这个语法。
二、适用场景
领域特定语言复杂输入解释可扩展的语言结构
三、UML类图 四、案例
对输入的特定格式的打印语句进行解析并执行。
packag…一、简介
解释器模式为某个语言定义它的语法或者叫文法表示并定义一个解释器用来处理这个语法。
二、适用场景
领域特定语言复杂输入解释可扩展的语言结构
三、UML类图 四、案例
对输入的特定格式的打印语句进行解析并执行。
package mainimport (fmtstrconvstrings
)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 intExpression 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 Hellowords : 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()}
}