首页 > 代码库 > 《面向对象的计算器》

《面向对象的计算器》

package com.lewang;

import java.util.HashMap;
import java.util.Map;

abstract class Operator {
public final String op;

public Operator(String op) {
this.op = op;
}

public double op(String lhs, String rhs) {
double a = Double.parseDouble(lhs);
double b = Double.parseDouble(rhs);
return opImpl(a, b);
}

protected abstract double opImpl(double lhs, double rhs);
}

class OperatorAdd extends Operator {
public OperatorAdd() {
super("+");
}

@Override
public double opImpl(double lhs, double rhs) {
return 0;
}
}

class OperatorSub extends Operator {
public OperatorSub() {
super("-");
}

@Override
public double opImpl(double lhs, double rhs) {
return 0;
}
}

class Calculator {
private Map<String, Operator> operatorMap = new HashMap<>();

public Calculator() {
}

public Calculator addOperator(Operator operator) {
this.operatorMap.put(operator.op, operator);
return this;
}

public double calculate(String op, String lhs, String rhs) throws IllegalArgumentException {
if (!this.operatorMap.containsKey(op)) throw new IllegalArgumentException("unknown operator");
return this.operatorMap.get(op).op(lhs, rhs);
}
}

public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.addOperator(new OperatorAdd() {
@Override
public double opImpl(double lhs, double rhs) {
return lhs + rhs;
}
}).addOperator(new OperatorSub() {
@Override
public double opImpl(double lhs, double rhs) {
return lhs - rhs;
}
});
System.out.println(calculator.calculate("+", "1.0", "2.0"));
}
}

《面向对象的计算器》