# 简单工厂

2012/09/17 21:44

Demo 简单计算器实现：

OperationFactory就是一个生产具体运算子类的简单工厂。

/**
* @说明：运算类父类
*
* */
public class Operation {
protected double numberA = 0;
protected double numberB = 0;

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() {
double result = 0;
return result;
}

}

/**
* @说明：加法运算
*
* */
public class OperationAdd extends Operation {
@Override
public double getResult(){
double result=0;
result=numberA+numberB;
return result;
}
}
/**
* @说明：减法运算
*
* */
public class OperationSub extends Operation {
@Override
public double getResult() {
double result = 0;
result = numberA - numberB;
return result;
}
}
/**
* @说明：乘法运算
*
* */
public class OperationMul extends Operation {
@Override
public double getResult() {
double result = 0;
result = numberA * numberB;
return result;
}
}

/**
* @说明：除法运算
*
* */
public class OperationDiv extends Operation {
@Override
public double getResult() {
double result = 0;
result = numberA / numberB;
return result;
}
}
/**
* @说明：简单工厂，根据传入的运算符，来确定调用那个Operation的具体子类。
*
* */
public class OperationFactory {
public static Operation createOperate(String operate) {
Operation oper = null;
OperateType operateType = OperateType.getOperateType(operate);
switch (operateType) {
break;
case SUBTRACT:
oper = new OperationSub();
break;
case MULTIPLY:
oper = new OperationMul();
break;
case DIVIDE:
oper = new OperationDiv();
break;
default:
break;
}
return oper;
}
}
/**
* @author mengfei1001
* @说明：计算器运算符枚举
*
* */
public enum OperateType {
private String value;

private OperateType(String value) {
this.value = value;

}

public static OperateType getOperateType(String type) {
if (type == null) {
}
for (OperateType t : OperateType.values()) {
if (t.value.equals(type)) {
return t;
}
}
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

}
/**
* @说明：测试类
*
* */
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字A：");
double numberA = sc.nextDouble();
System.out.println("请选择运算符号(+、-、*、/):");
String operate = sc.next();
System.out.println("请输入数字B：");
double numberB = sc.nextDouble();
Operation oper = OperationFactory.createOperate(operate);
oper.setNumberA(numberA);
oper.setNumberB(numberB);
double result = oper.getResult();
System.out.println(result);
}
}

0 评论
0 收藏
0