码迷,mamicode.com
首页 > 其他好文 > 详细

《面向对象的计算器》

时间:2017-06-27 01:09:14      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:public   family   sub   super   abstract   int   对象   package   计算   

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

《面向对象的计算器》

标签:public   family   sub   super   abstract   int   对象   package   计算   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!