File tree Expand file tree Collapse file tree 1 file changed +55
-1
lines changed Expand file tree Collapse file tree 1 file changed +55
-1
lines changed Original file line number Diff line number Diff line change 1- // 解释器模式(Interpreter Pattern)
1+ // 解释器模式(Interpreter Pattern)
2+
3+ // 定义对于语法的断言
4+ class TerminalExpression {
5+ constructor ( data ) {
6+ this . data = data
7+ }
8+
9+ interpret ( context ) {
10+ if ( context . indexOf ( this . data ) > - 1 ) {
11+ return true
12+ }
13+ return false
14+ }
15+ }
16+
17+ // 添加表达式判断符
18+ class OrExpression {
19+ constructor ( expr1 , expr2 ) {
20+ this . expr1 = expr1 ;
21+ this . expr2 = expr2 ;
22+ }
23+ interpret ( context ) {
24+ return this . expr1 . interpret ( context ) || this . expr2 . interpret ( context ) ;
25+ }
26+ }
27+ class AndExpression {
28+ constructor ( expr1 , expr2 ) {
29+ this . expr1 = expr1 ;
30+ this . expr2 = expr2 ;
31+ }
32+ interpret ( context ) {
33+ return this . expr1 . interpret ( context ) && this . expr2 . interpret ( context ) ;
34+ }
35+ }
36+
37+
38+ // 获取对应表达式
39+ function getMaleExpression ( ) {
40+ const robert = new TerminalExpression ( "Robert" ) ;
41+ const john = new TerminalExpression ( "John" ) ;
42+ return new OrExpression ( robert , john ) ;
43+ }
44+ function getMarriedWomanExpression ( ) {
45+ const julie = new TerminalExpression ( "Julie" ) ;
46+ const married = new TerminalExpression ( "Married" ) ;
47+ return new AndExpression ( julie , married ) ;
48+ }
49+
50+
51+ // 判断语句断言
52+ const isMale = getMaleExpression ( ) ;
53+ const isMarriedWoman = getMarriedWomanExpression ( ) ;
54+ console . log ( "John is male? " + isMale . interpret ( "John" ) ) ;
55+ console . log ( "Julie is a married women? " )
You can’t perform that action at this time.
0 commit comments