Skip to content

Commit ac5cf82

Browse files
committed
Interpreter Pattern - And and Or expression example
1 parent 9c1b402 commit ac5cf82

File tree

1 file changed

+93
-0
lines changed
  • InterpreterPattern/src/com/premaseem/interpreterPattern/andOrExpression

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.premaseem.interpreterPattern.andOrExpression;
2+
3+
import java.util.Scanner;
4+
5+
public class ClientFile {
6+
7+
8+
//Rule: Robert and John are male
9+
public static Expression getMaleExpression(){
10+
Expression robert = new TerminalExpression("Robert");
11+
Expression john = new TerminalExpression("John");
12+
return new OrExpression(robert, john);
13+
}
14+
15+
//Rule: Julie is a married women
16+
public static Expression getMarriedWomanExpression(){
17+
Expression julie = new TerminalExpression("Julie");
18+
Expression married = new TerminalExpression("Married");
19+
return new AndExpression(julie, married);
20+
}
21+
22+
public static void main(String[] args) {
23+
24+
System.out.println("Interpeter expression ");
25+
Scanner scan = new Scanner(System.in);
26+
27+
Expression isMale = getMaleExpression();
28+
Expression isMarriedWoman = getMarriedWomanExpression();
29+
30+
System.out.println("John is male? " + isMale.interpret("John"));
31+
System.out.println("Julie is a married women? "
32+
+ isMarriedWoman.interpret("Married Julie"));
33+
System.out.println("\n $$$$$$$$$$$$$$$$$$$$ Thanks by Prem Aseem $$$$$$$$$$$$$$$$$$$$$$ \n ");
34+
System.out.println("\n $$$$$$$$$$$$$$$$$$$$$ www.premaseem.com $$$$$$$$$$$$$$$$$$$$$$ \n ");
35+
36+
}
37+
38+
39+
40+
}
41+
42+
interface Expression {
43+
public boolean interpret(String context);
44+
}
45+
46+
class TerminalExpression implements Expression {
47+
48+
private String data;
49+
50+
public TerminalExpression(String data){
51+
this.data = data;
52+
}
53+
54+
@Override
55+
public boolean interpret(String context) {
56+
if(context.contains(data)){
57+
return true;
58+
}
59+
return false;
60+
}
61+
}
62+
63+
class OrExpression implements Expression {
64+
65+
private Expression expr1 = null;
66+
private Expression expr2 = null;
67+
68+
public OrExpression(Expression expr1, Expression expr2) {
69+
this.expr1 = expr1;
70+
this.expr2 = expr2;
71+
}
72+
73+
@Override
74+
public boolean interpret(String context) {
75+
return expr1.interpret(context) || expr2.interpret(context);
76+
}
77+
}
78+
79+
class AndExpression implements Expression {
80+
81+
private Expression expr1 = null;
82+
private Expression expr2 = null;
83+
84+
public AndExpression(Expression expr1, Expression expr2) {
85+
this.expr1 = expr1;
86+
this.expr2 = expr2;
87+
}
88+
89+
@Override
90+
public boolean interpret(String context) {
91+
return expr1.interpret(context) && expr2.interpret(context);
92+
}
93+
}

0 commit comments

Comments
 (0)