-
Notifications
You must be signed in to change notification settings - Fork 1
/
InterpreterPattern2.java
77 lines (56 loc) · 1.83 KB
/
InterpreterPattern2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package DesignPatterns.BehaviouralDesignPattern;
public class InterpreterPattern2 {
public static void main(String[] args) {
Expression persion1 = new TerminalExpression("jack");
Expression persion2 = new TerminalExpression("rose");
Expression isSingle = new OrExpresssion(persion1,persion2);
Expression persion3 = new TerminalExpression("virat");
Expression persion4 = new TerminalExpression("anushka");
Expression isMarried = new AndExpression(persion3, persion4);
System.out.println(isSingle.interpret("jack"));
System.out.println(isSingle.interpret("rose"));
System.out.println(isSingle.interpret("Alfred"));
System.out.println(isMarried.interpret("anushka, virat"));
System.out.println(isMarried.interpret("priyanka, virat"));
}
}
interface Expression{
boolean interpret(String contex);
}
// leaf terminal expression
class TerminalExpression implements Expression{
String data;
public TerminalExpression(String data) {
this.data = data;
}
@Override
public boolean interpret(String contex) {
return contex.contains(data);
}
}
// Non Terminal Expression
class OrExpresssion implements Expression{
Expression e1;
Expression e2;
public OrExpresssion(Expression e1, Expression e2) {
this.e1 = e1;
this.e2 = e2;
}
@Override
public boolean interpret(String contex) {
return e1.interpret(contex) || e2.interpret(contex);
}
}
// Non Terminal expression
class AndExpression implements Expression{
Expression e1;
Expression e2;
public AndExpression(Expression e1, Expression e2) {
this.e1 = e1;
this.e2 = e2;
}
@Override
public boolean interpret(String contex) {
return e1.interpret(contex) && e2.interpret(contex);
}
}