In web programming, we often use regular expression for validating the e-mail address or phone number. Regular expression is a powerful tool in validating the specific format field. However, the interpretation of regular expression is not an easy job.
In the GoF’s design patterns, there is a corresponding pattern named Interpreter.
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
–By GOF BOOK
Maybe, from the intent, you’ll know that you won’t touch this pattern in your future career
That’s what I think.
To illustrate this pattern, I’ll show you a demo for calculating an arithmetic expression. And the expression will only support addition and subtraction, so the expression may looks like “11 + 2 + 3 - 4 – 5 + 8”.
And the grammar we define as follows:
GeneralExpression => AddExpression | SubExpression | NumberExpression
AddExpression => GeneralExpression + NumberExpression
SubExpression => GeneralExpression - NumberExpression
NumberExpression => 0 | ([1-9][0-9]*)
Note: “|” means or.
Now, the expression “11 + 2 + 3 - 4 – 5 + 8”’s grammar tree can be describe as follows.
As you see, we can calculate the expression by parsing the expression from top to down. Now, we need to design the classes.
The class diagram is as follows.
When we get an expression, it’ll be passed to the GeneralExpression, then the interpret method will be called. The source code is as follows.
- public function interpret () : int
- {
- if ( exp . lastIndexOf ( " + " ) > exp . lastIndexOf ( " - " ))
- return new AddExpression ( exp ) . interpret () ;
- else if ( exp . lastIndexOf ( " + " ) < exp . lastIndexOf ( " - " ))
- return new SubExpression ( exp ) . interpret () ;
- else
- return new NumberExpression ( exp ) . interpret () ;
- }
And the interpret method of SubExpression or AddExpression maybe called, and here is the source code of interpret method in SubExpression.
- public function interpret () : int
- {
- var index : int = exp . lastIndexOf ( SUB ) ;
- var generalExp : String = exp . substr ( 0 , index ) ;
- var numberExp : String = exp . substr ( index + 1 , exp . length ) ;
- return new GeneralExpression ( generalExp ) . interpret ()
- - new NumberExpression ( numberExp ) . interpret () ;
- }
In the interpret method of each class will parsing the expression from top to down, then calculate the value and returns it.
As you see, this pattern is, eh, all about the complier
I don’t like this pattern, because it’s uneasy to implement when the grammar is not so simple. Maybe it’s all because I haven’t learned the complier principle well.
Download Full Project
Enjoy!
本文介绍了解释器模式在计算算术表达式中的应用,并通过一个简单的加减法表达式解析案例进行演示。该模式定义了语言的文法规则及其解释器,能够从上至下解析并计算表达式的值。
6万+

被折叠的 条评论
为什么被折叠?



