工厂模式实现

2023-12-13 08:59:15

通过一个工厂来提供对应的实现类

实现一个计算器

  1. 实现一个计算接口(BaseCompute)

  2. 具体的实现方法继承接口

  3. 实现一个工厂,通过传入给定的值来返回特定的接口实现类

    Factory factory = new Factory();
    BaseCompute compute = factory.getCompute("(给定条件)");
    compute.compute();
    

具体实现类

public abstract class BaseCompute {
    private Integer Number1;

    public Integer getNumber1() {
        return Number1;
    }

    public void setNumber1(Integer number1) {
        Number1 = number1;
    }

    public Integer getNumber2() {
        return Number2;
    }

    public void setNumber2(Integer number2) {
        Number2 = number2;
    }

    private Integer Number2;

    public abstract Double compute(Integer number1, Integer number2);


}

class AddCompute  extends BaseCompute{
    @Override
    public Double compute(Integer number1, Integer number2) {
        return (double) (number2+number1);
    }
}

class SubCompute  extends BaseCompute{
    public SubCompute() {

    }

    @Override
    public Double compute(Integer number1, Integer number2) {
        return (double) (number1-number2);
    }
}

class MultiCompute  extends BaseCompute{
    @Override
    public Double compute(Integer number1, Integer number2) {
        return (double) (number1*number2);
    }
}

class DivCompute  extends BaseCompute{
    @Override
    public Double compute(Integer number1, Integer number2) {
        return (double) (number1/number2);
    }
}

计算工厂

public class ComputeFactory {

    public BaseCompute getComputeFactory(String operation){
        BaseCompute compute;
        if (operation.equals("+")) {
            compute = new AddCompute();
        } else if (operation.equals("-")) {
            compute = new SubCompute();
        } else if (operation.equals("*")) {
            compute = new MultiCompute();
        } else if (operation.equals("/")) {
            compute = new DivCompute();
        } else {
            compute = null;
        }
        return compute;
    }

}

计算器

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();
        String operation = scanner.next();
        ComputeFactory computeFactory = new ComputeFactory();
        BaseCompute computeFactory1 = computeFactory.getComputeFactory(operation);
        Double compute = computeFactory1.compute(num1, num2);
        System.out.println(compute);
    }


文章来源:https://blog.csdn.net/weixin_44050153/article/details/134942787
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。