import
java.util.*;
interface
CalculatorOperation {
double
perform(
double
a,
double
b);
}
class
Calculator {
private
Map<String,
Class<?
extends
CalculatorOperation> >
operations;
public
Calculator() { operations =
new
HashMap<>(); }
public
void
registerOperation(
String name,
Class<?
extends
CalculatorOperation> operationClass)
{
operations.put(name, operationClass);
}
public
double
performOperation(String name,
double
a,
double
b)
{
Class<?
extends
CalculatorOperation> operationClass
= operations.get(name);
if
(operationClass ==
null
) {
throw
new
IllegalArgumentException(
"Unknown operation: "
+ name);
}
try
{
CalculatorOperation operation
= operationClass.getDeclaredConstructor()
.newInstance();
return
operation.perform(a, b);
}
catch
(Exception e) {
throw
new
IllegalStateException(
"Error instantiating operation"
, e);
}
}
}
public
class
Main {
public
static
void
main(String[] args)
{
Calculator calculator =
new
Calculator();
calculator.registerOperation(
"add"
,
AddOperation.
class
);
String operationName =
"add"
;
double
a =
7
, b =
9
;
try
{
double
result = calculator.performOperation(
operationName, a, b);
System.out.println(
"Result: "
+ result);
}
catch
(IllegalArgumentException e) {
System.out.println(
"Unknown operation: "
+ operationName);
}
catch
(IllegalStateException e) {
System.out.println(
"Error instantiating operation: "
+ e.getMessage());
}
}
}
class
AddOperation
implements
CalculatorOperation {
@Override
public
double
perform(
double
a,
double
b)
{
return
a + b;
}
}