简单计算器
今天看了下设计模式的简单工厂模式,对照着写了个简单的计算器,代码非常简单
运算符操作类
public abstract class OPerator {
private double numberA;
private double numberB;
private double result;
public double getNumberA() {
return numberA;
}
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public double getNumberB() {
return numberB;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
}
运算操作工厂
public class OpFactory{
public OPerator oPerator = null;
public OPerator compute(char opStr,double numberA, double numberB){
switch (opStr){
case '+':
oPerator = new Add(numberA,numberB);
break;
case'-':
oPerator = new Sub(numberA,numberB);
break;
case'*':
oPerator= new Mul(numberA,numberB);
break;
case'/':
oPerator = new Div(numberA, numberB);
break;
default:
System.out.println("计算错误!");
break;
}
return oPerator;
}
}
加减乘除运算实现
public class Add extends OPerator{
public Add(double numberA, double numberB){
this.setNumberA(numberA);
this.setNumberB(numberB);
this.setResult(this.getNumberA()+this.getNumberB());
}
}
public class Sub extends OPerator{
public Sub(double numberA, double numberB){
this.setNumberA(numberA);
this.setNumberB(numberB);
this.setResult(this.getNumberA()-this.getNumberB());
}
}
public class Mul extends OPerator{
public Mul(double numberA, double numberB){
this.setNumberA(numberA);
this.setNumberB(numberB);
this.setResult(this.getNumberA()*this.getNumberB());
}
}
public class Div extends OPerator{
public Div(double numberA, double numberB){
this.setNumberA(numberA);
this.setNumberB(numberB);
if(0 == this.getNumberB()){
try {
throw new Exception("除数不能为0");
} catch (Exception e) {
e.printStackTrace();
}
}else{
this.setResult(this.getNumberA()/this.getNumberB());
}
}
}
测试类
public class Mc {
@Test
public void addTest(){
System.out.println("请输入数字:");
Scanner scanner1 = new Scanner(System.in);
double numberA = scanner1.nextDouble();
System.out.println("请输入操作符:'+','-','*','/'");
Scanner sc = new Scanner(System.in);
String opStr = sc.nextLine();
System.out.println("请输入数字:");
Scanner scanner2 = new Scanner(System.in);
double numberB = scanner2.nextDouble();
OPerator oPerator = new OpFactory().compute(opStr.charAt(0),numberA,numberB);
System.out.println("结果:"+oPerator.getResult());
}
}
第一次写:若是有不对的地方,欢迎拍砖。其他的我也不会说话了,感觉没啥话,巴拉巴拉一大堆,想吐槽了.....拜拜,下次在写