通过一个工厂来提供对应的实现类
实现一个计算器
实现一个计算接口(BaseCompute)
具体的实现方法继承接口
实现一个工厂,通过传入给定的值来返回特定的接口实现类
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);
}