-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFactoryMode.java
117 lines (103 loc) · 2.34 KB
/
FactoryMode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package design_mode;
import object_oriented_programming.CommonConstants;
/**
* 工厂模式(简单工厂模式)
* 实现加减乘除简易计算器
* 由操作工厂根据不同运算符创建相应的操作类
*
* @author 唐龙
*
*/
public class FactoryMode {
public static void main(String[] args) {
double opNumA=Math.random()*CommonConstants.RANGE;//操作数1
double opNumB=Math.random()*CommonConstants.RANGE;//操作数2
char op = CommonConstants.OPERATIONS[(int)(Math.random()*4)];//运算符
//由操作工厂根据不同运算符创建相应的操作类
Operation operation = OperationFactory.createOperation(op);
operation.setOpNumA(opNumA);//设置操作数1
operation.setOpNumB(opNumB);//设置操作数2
double result=operation.getResult();//运算结果
System.out.printf("%.2f%c%.2f=%.2f%n",opNumA,op,opNumB,result);
}
}
//基本运算类
class Operation{
private double opNumA;//操作数1
private double opNumB;//操作数2
private double result=Double.MAX_VALUE;//运算结果
public Operation(){}
// getter and setter
public double getOpNumA() {
return opNumA;
}
public void setOpNumA(double opNumA) {
this.opNumA = opNumA;
}
public double getOpNumB() {
return opNumB;
}
public void setOpNumB(double opNumB) {
this.opNumB = opNumB;
}
public double getResult() {
return result;
}
}
//加法类
class OpAdd extends Operation{
@Override
public double getResult() {
return getOpNumA()+getOpNumB();
}
}
//减法类
class OpMinus extends Operation{
@Override
public double getResult() {
return getOpNumA()-getOpNumB();
}
}
//乘法类
class OpMultiply extends Operation{
@Override
public double getResult() {
return getOpNumA()*getOpNumB();
}
}
//除法类
class OpDivide extends Operation{
@Override
public double getResult() {
if((int)getOpNumB()!=0) {
return getOpNumA()/getOpNumB();
}else{
System.out.println("除数不允许为0。");//除数为0
return Double.NaN;
}
}
}
//操作工厂类
class OperationFactory{
//获取运算对象
public static Operation createOperation(char op){
Operation operation=null;
switch(op){
case '+':
operation=new OpAdd();
break;
case '-':
operation=new OpMinus();
break;
case '*':
operation=new OpMultiply();
break;
case '/':
operation=new OpDivide();
break;
default:
operation=new Operation();
}
return operation;
}
}