Java – implementation instances in interfaces
In my project, I need to create objects for each Java math operator, such as "add", "substitution", "multiplication", etc These operators should be singletons
So here's what I'm going to do I define math operator as an interface, and I put these implementations in it because 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; } }; }
When I do this, I don't see many such usages So I wonder if this is a good practice, if there is a better and more elegant method?
Solution
I can do SMT like
1) Define interface
interface MathOperator { double operate(double a,double b); }
2) There are some common implementations (less code) in enumerations
enum MathOperators implements MathOperator { ADD { @Override public double operate(double a,double b) { return a + b; } },SUBTRACT { @Override public double operate(double a,double b) { return a - b; } } }
3) Or public static members (cleaner solutions)
class MathOperators { public static MathOperator ADD = new MathOperator() { @Override public double operate(double a,double b) { return a + b; } }; public static MathOperator SUBTRACT = new MathOperator() { @Override public double operate(double a,double b) { return a - b; } }; }
>You can create new mathoperators without changing mathoperators > there are good APIs for common operations > should not write singles > there is a clean interface