首页 > 其他 > 详细

《面向对象的计算器》

时间:2017-06-27 00:28:45      阅读:360      评论:0      收藏:0      [点我收藏+]

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"));
}
}

《面向对象的计算器》

原文:http://www.cnblogs.com/intelligentfish/p/7083028.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!