Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In my project I need to create objects for each kind of Java Math Operator like

ID: 3638389 • Letter: I

Question

In my project I need to create objects for each kind of Java Math Operator like "Add", "Multiplication", "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?

Explanation / Answer

I use this pattern often, especially for specific implementations of generic interfaces. I find it works really well for me.

I like the way it puts the implementations where you can find them. I do it slightly differently - I make them static (it's a style thing, so the interface impls look more like class impls):

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote