Strategy Pattern
Completed
Write interface Operation (long apply(long a, long b)) and store implementations in a Map<String, Operation> for add, sub, mul, max. Read op a b lines and print the results or unknown op. Use anonymous classes (no lambdas yet).
Input
n, then n lines.
Output
n lines.
Example
Input
4 add 2 3 mul 4 5 max -1 -9 pow 2 3
Output
5 20 -1 unknown op
Editor
Java
Hints
new Operation() { ... } creates an anonymous class implementing the interface.
Solution explanation
Choosing behaviour by looking up an object is the strategy pattern. Lambdas (chapter 21) make it shorter.
Show solution
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
interface Operation {
long apply(long a, long b);
}
public class Main {
public static void main(String[] args) {
Map<String, Operation> ops = new HashMap<String, Operation>();
ops.put("add", new Operation() {
public long apply(long a, long b) { return a + b; }
});
ops.put("sub", new Operation() {
public long apply(long a, long b) { return a - b; }
});
ops.put("mul", new Operation() {
public long apply(long a, long b) { return a * b; }
});
ops.put("max", new Operation() {
public long apply(long a, long b) { return Math.max(a, b); }
});
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String name = sc.next();
long a = sc.nextLong(), b = sc.nextLong();
Operation op = ops.get(name);
System.out.println(op == null ? "unknown op" : String.valueOf(op.apply(a, b)));
}
}
}