-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathDemo.java
More file actions
71 lines (57 loc) · 2.34 KB
/
Demo.java
File metadata and controls
71 lines (57 loc) · 2.34 KB
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
package refactoring_guru.behavioral.interpreter.example;
import refactoring_guru.behavioral.interpreter.example.expressions.AndExpression;
import refactoring_guru.behavioral.interpreter.example.expressions.Context;
import refactoring_guru.behavioral.interpreter.example.expressions.OrExpression;
import refactoring_guru.behavioral.interpreter.example.expressions.VariableExpression;
/**
* EN: Interpreter Design Pattern
*
* Defines a representation for a grammar as well as a mechanism to understand and act upon the grammar.
*
* RU: Паттерн Интерпретатор
*
* Определяет грамматику простого языка, представляет предложения на этом языке и интерпретирует их.
*/
public class Demo {
private static void example1() throws Exception {
var context = new Context();
var a = new VariableExpression("A");
var b = new VariableExpression("B");
var c = new VariableExpression("C");
// example 1:
// A ∧ (B ∨ C)
var example1 = new AndExpression(
a,
new OrExpression(b, c)
);
context.assign(a, true);
context.assign(b, true);
context.assign(c, false);
var result = example1.interpret(context) ? "true" : "false";
System.out.println("boolean expression A ∧ (B ∨ C) = " + result + ", with variables A=true, B=true, C=false");
}
private static void example2() throws Exception {
var context = new Context();
var a = new VariableExpression("A");
var b = new VariableExpression("B");
var c = new VariableExpression("C");
// example 2:
// B ∨ (A ∧ (B ∨ C))
var example2 = new OrExpression(
b,
new AndExpression(
a,
new OrExpression(b, c)
)
);
context.assign(a, false);
context.assign(b, false);
context.assign(c, true);
var result2 = example2.interpret(context) ? "true" : "false";
System.out.println("boolean expression B ∨ (A ∧ (B ∨ C)) = " + result2 + ", with variables A=false, B=false, C=true");
}
public static void main(String[] args) throws Exception {
example1();
example2();
}
}