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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>