第1章 代码无错就是优?——简单工厂模式(Java)
简单工厂模式(Simple Factory):又叫静态方法模式,因为工厂类定义了一个静态方法 ,给这个静态方法传入不同的参数可以获得不同的对象。
- 依赖:函数中使用了箭头指向的类对象
- 关联:本类的成员变量是箭头指向的类对象
- 泛化:继承了箭头指向的类
/**
* @CreateTime: 2021/02/15 13:49
* @Description: 简单工厂模式:计算器
*/
public class SimpleFactoryComparator {
public static void main(String[] args) {
// 使用缓冲流读取控制台输入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("请输入第一个数字:");
double first = Double.parseDouble(br.readLine());
System.out.println("请输入操作符(+、-、*、/);");
Operation operation = OperationFactory.createOperation(br.readLine());
System.out.println("请输入第二个数字:");
double second = Double.parseDouble(br.readLine());
operation.setFirst(first);
operation.setSecond(second);
System.out.println("结果是:" + operation.getResult());
} catch (IOException e) {
e.printStackTrace();
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
class Operation {
private double first = 0;
private double second = 0;
public double getFirst() {
return first;
}
public void setFirst(double first) {
this.first = first;
}
public double getSecond() {
return second;
}
public void setSecond(double second) {
this.second = second;
}
public double getResult() {
return 0;
}
}
class OperationAdd extends Operation {
@Override
public double getResult() {
return getFirst() + getSecond();
}
}
class OperationSub extends Operation {
@Override
public double getResult() {
return getFirst() / getSecond();
}
}
class OperationMul extends Operation {
@Override
public double getResult() {
return getFirst() * getSecond();
}
}
class OperationDiv extends Operation {
@Override
public double getResult() {
// 除零判断
if (getSecond() == 0) {
throw new ArithmeticException("除数为零");
}
return getFirst() / getSecond();
}
}
class OperationFactory {
public static Operation createOperation(String operation) {
Operation result = null;
switch (operation) {
case "+":
result = new OperationAdd();
break;
case "-":
result = new OperationSub();
break;
case "*":
result = new OperationMul();
break;
case "/":
result = new OperationDiv();
break;
}
return result;
}
}