Java设计模式之四(经典面试题:工厂模式在开发中的运用)

时间:2020-11-28 14:10:25

原地址:http://www.tuicool.com/articles/ma2I3u

面试题: 
      写一个简单的计算器。 

代码实现:

抽象一个运算类:

package com.qianyan.calcuator;

public abstract class Operation {

//数字一
private double num1;

//数字二
private double num2;

public double getNum1() {
return num1;
}

public void setNum1(double num1) {
this.num1 = num1;
}

public double getNum2() {
return num2;
}

public void setNum2(double num2) {
this.num2 = num2;
}

public abstract double getResult();
}
创建工厂类:
package com.qianyan.factory;

import com.qianyan.calcuator.AddOperation;
import com.qianyan.calcuator.Operation;
import com.qianyan.calcuator.SubtractOperation;

public class OperationFactory {

public static Operation getOperation(String oper){
if("+".equals(oper))
return new AddOperation();
else if("-".equals(oper))
return new SubtractOperation();
else
return null;
}
}
抽象运算的实现类:
package com.qianyan.calcuator;

public class AddOperation extends Operation{

@Override
public double getResult() {
return this.getNum1() + this.getNum2();
}

}
package com.qianyan.calcuator;

public class SubtractOperation extends Operation{

@Override
public double getResult() {
return this.getNum1() - this.getNum2();
}

}
用户类:
package com.qianyan.user;

import java.util.Scanner;

import com.qianyan.calcuator.Operation;
import com.qianyan.factory.OperationFactory;

public class User {

public static void main(String[] args) {
System.out.println("----小C计算器程序----");
Scanner input = new Scanner(System.in);
System.out.println("请输入第一个运算数字:");
String str1 = input.nextLine();
System.out.println("请输入运算符:");
String oper = input.nextLine();
System.out.println("请输入第二个运算数字:");
String str2 = input.nextLine();

double num1 = Double.parseDouble(str1);
double num2 = Double.parseDouble(str2);

Operation opertion = OperationFactory.getOperation(oper);
opertion.setNum1(num1);
opertion.setNum2(num2);
double result = opertion.getResult();

System.out.println(str1 + oper + str2 + "=" + result);
}
}
测试结果:
----小C计算器程序----
请输入第一个运算数字:
5
请输入运算符:
-
请输入第二个运算数字:
3
5-3=2.0