-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinOpAgent.java
More file actions
79 lines (65 loc) · 2.45 KB
/
Copy pathBinOpAgent.java
File metadata and controls
79 lines (65 loc) · 2.45 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
72
73
74
75
76
77
78
79
// BinOpAgent.java
package test;
import java.util.function.BinaryOperator;
import test.TopicManagerSingleton.TopicManager;
public class BinOpAgent implements Agent {
private String name;
private Message input1 = null;
private Message input2 = null;
private String outputTopic;
private BinaryOperator<Double> operator;
private TopicManager tm;
private String topic1, topic2;
public BinOpAgent(String name, String topic1, String topic2, String output, BinaryOperator<Double> operator) {
this.name = name;
this.outputTopic = output;
this.operator = operator;
this.topic1 = topic1;
this.topic2 = topic2;
// TopicManager קבלת המופע היחיד של
this.tm = TopicManagerSingleton.get();
// הרשמה לנושאי הקלט
tm.getTopic(topic1).subscribe(this);
tm.getTopic(topic2).subscribe(this);
// הוספת הסוכן כמפרסם לנושא הפלט
tm.getTopic(output).addPublisher(this);
}
@Override
public String getName() {
return name;
}
@Override
public void reset() {
input1 = new Message("0");
input2 = new Message("0");
}
@Override
public void callback(String topic, Message msg) {
// שמירת ההודעה בקלט המתאים לפי נושא הקלט
if (topic.equals(topic1)) {
input1 = msg;
} else if (topic.equals(topic2)) {
input2 = msg;
}
// אם יש ערכים בשני הקלטים, מבצע את החישוב
if (input1 != null && input2 != null) {
try {
double val1 = input1.asDouble;
double val2 = input2.asDouble;
// הפעלת הפעולה הבינארית וחישוב התוצאה
double result = operator.apply(val1, val2);
// פרסום התוצאה לנושא הפלט
tm.getTopic(outputTopic).publish(new Message(result));
} catch (Exception e) {
// במקרה של שגיאה בהמרה או בחישוב
System.err.println("Error in calculation: " + e.getMessage());
}
}
}
@Override
public void close() {
// ניתוק מכל הנושאים
input1 = null;
input2 = null;
}
}