1.设计计算的基类,封装计算的一些通用方法,所有类型的计算都继承这个基类
* 计算基类
*
* @author WangPeng
*
* Operation.java 2015年9月28日 上午9:57:23
*/
public abstract class Operation {
protected abstract double getResult(double numA, double numB) throws Exception;
}
/**
* 加法计算类
*
* @author WangPeng
*
* OperationAdd.java 2015年9月28日 上午10:06:31
*/
public class OperationAdd extends Operation {
@Override
protected double getResult(double numA, double numB) {
return numA + numB;
}
}
/**
* 减法计算类
*
* @author WangPeng
*
* OperationSub.java 2015年9月28日 上午10:08:20
*/
public class OperationSub extends Operation {
@Override
protected double getResult(double numA, double numB) {
return numA - numB;
}
}
/**
* 乘法计算类
*
* @author WangPeng
*
* OperationMul.java 2015年9月28日 上午10:09:37
*/
public class OperationMul extends Operation {
@Override
protected double getResult(double numA, double numB) {
return numA * numB;
}
}
/**
* 除法计算类
*
* @author WangPeng
*
* OperationDiv.java 2015年9月28日 上午10:10:34
*/
public class OperationDiv extends Operation {
@Override
protected double getResult(double numA, double numB) throws Exception {
if (numB == 0) {
throw new Exception("除数不能为0");
}
return numA / numB;
}
}
/**
* 工厂类
*
* @author WangPeng
*
* OperationFactory.java 2015年9月28日 上午10:23:29
*/
public class OperationFactory {
public static Operation createOperation(String operate) throws Exception {
switch (operate) {
case "+":
return new OperationAdd();
case "-":
return new OperationSub();
case "*":
return new OperationMul();
case "/":
return new OperationDiv();
default:
throw new Exception("暂时不支持该类计算");
}
}
}
4.测试运行
/**
* 测试类
*
* @author WangPeng
*
* Test.java 2015年9月28日 上午10:16:37
*/
public class Test {
public static void main(String[] args) {
try {
// 计算2 + 3 = ?
Operation operation = OperationFactory.createOperation("+");
//输出5.0
System.out.println(operation.getResult(2, 3));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上实现的是一种简单的工厂模式,通过这种模式可以降低代码的耦合,便于维护和扩展