标签:logs 工厂模式 ack return port get main dev 运算
Operator.java 类:
package sampleFactory; import java.math.BigDecimal; public abstract class Operator { BigDecimal numA; BigDecimal numB; BigDecimal result ; public abstract BigDecimal getResult(); }
OperatorAdd.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorAdd extends Operator { @Override public BigDecimal getResult() { System.out.println(numA); System.out.println(numB); result = numA.add(numB); return result; } }
OperatorDevide.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorDevide extends Operator { @Override public BigDecimal getResult() { result = numA.divide(numB); return result; } }
OperatorMul.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorMul extends Operator { @Override public BigDecimal getResult() { result = numA.multiply(numB); return result; } }
OperatorSub.java类
package sampleFactory; import java.math.BigDecimal; public class OperatorSub extends Operator { @Override public BigDecimal getResult() { result = numA.subtract(numB); return result; } }
SampleFactory.java类
package sampleFactory; public class SampleFactory { Operator op ; public Operator createOperator(String operator){ switch(operator){ case "+": op = new OperatorAdd(); break; case "-": op = new OperatorSub(); break; case "*": op = new OperatorMul(); break; case "/": op = new OperatorDevide(); } return op ; } }
Business.java类
package sampleFactory; import java.math.BigDecimal; import java.util.Scanner; public class Business { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入数字A:"); BigDecimal numA = sc.nextBigDecimal(); System.out.println("请输入操作符:"); String operator = sc.next(); System.out.println("请输入数字B:"); BigDecimal numB = sc.nextBigDecimal(); SampleFactory sf = new SampleFactory(); Operator op = sf.createOperator(operator); op.numA = numA ; op.numB = numB ; BigDecimal result = op.getResult(); System.out.println("运算结果:"+result); sc.close(); } }
标签:logs 工厂模式 ack return port get main dev 运算
原文地址:http://www.cnblogs.com/ccgjava/p/7015544.html