【设计模式】简单工厂模式

文章目录


问题:
简单写一个计算器,输入2个数和运算符,得到结果。

分析:
这一题看上去很简单,但如果面试时你写的是下面这种代码,那大概率是过不了的。
【设计模式】简单工厂模式_第1张图片
上面代码也能实现题目的功能,但是代码没有错就是好的吗?
以上代码复用性低;可维护性差,如果要改+的逻辑,就会牵一发而动全身;扩展性差,如果这个时候新增开平方的逻辑怎么办?

以下介绍一个简单的设计模式,大家可以带着上面的问题分析一下以下代码:
简单工厂模式:用一个类来创造实例的过程。
【设计模式】简单工厂模式_第2张图片

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;
    }
}

你可能感兴趣的:(设计模式,设计模式,简单工厂模式)