简单工厂模式

目的:通过继承操作类,将单个操作分离出来,前端通过工厂类获取实现对象。
用到:继承、多态、封装
factory-》operation-》getResult()

前端通过调用工厂类获取具体实现对象

import java.util.Scanner;

public class main {

    //实现计算器的功能,输入2个数字和1个运算符号
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        double numOne = sc.nextDouble();
        sc = new Scanner(System.in);
        String operate = sc.nextLine();
        sc = new Scanner(System.in);
        double numTwo = sc.nextDouble();
        operation operation = operationFactory.createOperation(operate);
        operation.setNumA(numOne);
        operation.setNumB(numTwo);
        double result = operation.getResult();
        System.out.println(result);
    }
}

写一个工厂类,获取具体对象,这里也可以通过反射获取具体对象

public class operationFactory {

    public static operation createOperation(String operate){
        operation oper = null;
        switch (operate){
            case "+":
                oper = new operationAdd();
                break;
            case "-":
                oper = new operationSub();
                break;
        }
        return oper;
    }
}

具体实现类

public class operation {

    private double numA = 0;
    private double numB = 0;

    public double getNumA() {
        return numA;
    }

    public void setNumA(double numA) {
        this.numA = numA;
    }

    public double getNumB() {
        return numB;
    }

    public void setNumB(double numB) {
        this.numB = numB;
    }

    public double getResult(){
        double result = 0;
        return result;
    }
}

具体实现,重写getResult()方法

public class operationAdd extends operation {

    @Override
    public double getResult(){
        return getNumA()+getNumB();
    }
}
Connected to the target VM, address: '127.0.0.1:39957', transport: 'socket'
5
+
4
9.0
Disconnected from the target VM, address: '127.0.0.1:39957', transport: 'socket'

Process finished with exit code 0

相关推荐