In my project I need to create objects for each kind of Java Math Operator like "Add", "Substraction", "Multiplication", etc. And these operators should be singletons.
So here is what I am going to do. I define the Math Operator as an interface and I put those implementations inside it as I don't want to define singleton classes for each operator.
public interface MathOperator {
double operate(double a, double b);
MathOperator ADD = new MathOperator(){
@Override
public double operate(double a, double b) {
return a + b;
}
};
MathOperator SUBSTRACT = new MathOperator(){
@Override
public double operate(double a, double b) {
return a - b;
}
};
}
I don't see much of such usage when I Google this. So I wonder if this is a good practice and if there are better and more graceful approaches?