首页 > 代码库 > 《面向对象的计算器》
《面向对象的计算器》
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"));
}
}
《面向对象的计算器》
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。