分析:
这一题看上去很简单,但如果面试时你写的是下面这种代码,那大概率是过不了的。
上面代码也能实现题目的功能,但是代码没有错就是好的吗?
以上代码复用性低;可维护性差,如果要改+的逻辑,就会牵一发而动全身;扩展性差,如果这个时候新增开平方的逻辑怎么办?文章来源:https://www.toymoban.com/news/detail-663134.html
以下介绍一个简单的设计模式,大家可以带着上面的问题分析一下以下代码:
简单工厂模式:用一个类来创造实例的过程。
文章来源地址https://www.toymoban.com/news/detail-663134.html
package Chapter1;
import java.util.Objects;
import java.util.Scanner;
import Chapter1.operation.Operation;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数:");
Double firstNum = sc.nextDouble();
System.out.print("请输入运算符:");
String operationSymbol = sc.next();
System.out.println("请输入第二个数:");
Double secondNum = sc.nextDouble();
Operation operation = new OperationFactory().createOperation(operationSymbol);
while(Objects.isNull(operation)){
System.out.println("运算符输入错误,请重新输入");
operationSymbol = new Scanner(System.in).next();
operation = new OperationFactory().createOperation(operationSymbol);
}
operation.setFirstNum(firstNum);
operation.setSecondNum(secondNum);
System.out.print(operation.getResult());
}
}
package Chapter1;
import Chapter1.operation.*;
public class OperationFactory {
public Operation createOperation(String operation) {
switch (operation) {
case "+":
return new AddOperation();
case "-":
return new SubOperation();
case "*":
return new MutOperation();
case "/":
return new DivOperation();
}
return null;
}
}
package Chapter1.operation;
import lombok.Data;
@Data
public class Operation {
private Double firstNum;
private Double secondNum;
private Double result;
}
package Chapter1.operation;
import lombok.NonNull;
public class AddOperation extends Operation {
@Override
public Double getResult() {
return this.getFirstNum() + this.getSecondNum();
}
}
package Chapter1.operation;
import lombok.NonNull;
public class SubOperation extends Operation {
@Override
public Double getResult() {
return this.getFirstNum() - this.getSecondNum();
}
}
package Chapter1.operation;
import lombok.NonNull;
public class MutOperation extends Operation {
@Override
public Double getResult() {
return this.getFirstNum() * this.getSecondNum();
}
}
package Chapter1.operation;
import java.util.Scanner;
import lombok.NonNull;
public class DivOperation extends Operation {
@Override
public Double getResult() {
Double firstNum = this.getFirstNum();
Double secondNum = this.getSecondNum();
while (secondNum == 0) {
System.out.println("被除数不能为0, 请重新输入:");
secondNum = new Scanner(System.in).nextDouble();
}
return firstNum / secondNum;
}
}
到了这里,关于【设计模式】简单工厂模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!