刚看完《大话设计模式》第一章,上面使用简单工厂模式实现了四则运算,本文将改用java语言以及利用反射加简单工厂模式实现两个数的四则运算
1 首先给出四则运算的抽象父类
/**
*
* @author MAY
*
*/
abstract class AbstractOperation{
private double numberA;
private double numberB;
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;
}
abstract double getResult();
}
2 给出四则运算的子类,覆写getResult()方法
public class OperationAdd extends AbstractOperation {
@Override
double getResult() {
return this.getNumberA()+this.getNumberB();
}
}
public class OperationSubstract extends AbstractOperation{
@Override
double getResult() {
return this.getNumberA()-this.getNumberB();
}
}
public class OperationMultiply extends AbstractOperation {
@Override
double getResult() {
return this.getNumberA() * this.getNumberB();
}
}
public class OperationDivide extends AbstractOperation{
@Override
double getResult() {
return this.getNumberA()/this.getNumberB();
}
}
3 写出计算类
import java.util.Scanner;
/**
*
* @author MAY
*
*/
public class Caculator {
public static double caculate() throws Exception {
System.out.println("输入表达式,以空格分隔:");
Scanner scan = new Scanner(System.in);
String formula = scan.nextLine();
scan.close();
String[] results = StringProcess.Process(formula);
return Compute.Computor(results[0],results[1],results[2]);
}
public static void main(String[] args) throws Exception {
System.out.println(caculate());
}
}
class Compute{
public static double Computor(String numberA,String operation,String numberB) throws Exception {
AbstractOperation abstractOperation = Factory.getNewInstance(operation);//通过工厂获取运算子类实例,并通过父类接收,实现多态
abstractOperation.setNumberA(Double.parseDouble(numberA));
abstractOperation.setNumberB(Double.parseDouble(numberB));
return abstractOperation.getResult();
}
}
4 写出工厂类
public class Factory {
public static AbstractOperation getNewInstance(String operation) throws Exception {
String className = null;
switch(operation) {
case "+": className = "cn.dw.OperationAdd";break;
case "-": className = "cn.dw.OperationSubstract";break;
case "*": className = "cn.dw.OperationMultiply";break;
case "/": className = "cn.dw.OperationDivide";break;
}
return (AbstractOperation) Class.forName(className).newInstance(); //通过反射获取当前运算子类的实例化对象
}
}
5 写出输入处理类
这里只是简单讲输入进行限制和处理,更加的复杂的正则处理和鲁棒处理就不写了
public class StringProcess {
public static String[] Process(String formula) {
String regex = "[\s]+";
String[] result = formula.trim().split(regex);
return result;
}
}
6总结
通过一个简单的工厂模式和反射,以高内聚,低耦合为目标,实现了java的封装、继承和多态,且易于扩展。
比如我们想加入一个新的运算,则只需要写出新的计算子类,以及在工厂类中加入相应的case语句,获取新的子类实例即可。