Design Patterns in ActionScript-Interpreter
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!