forked from wenjy/design_patten_php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Operation.php
159 lines (146 loc) · 2.65 KB
/
Operation.php
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
<?php
/**
* 简单工厂模式
*
* 用一个工厂来创建我们所需要的类
*
* Class Operation
*/
class Operation
{
/**
* @var int
*/
private $numberA = 0;
/**
* @var int
*/
private $numberB = 0;
/**
* @return int
*/
public function getNumberA()
{
return $this->numberA;
}
/**
* @param int $numberA
*/
public function setNumberA($numberA)
{
$this->numberA = $numberA;
}
/**
* @return int
*/
public function getNumberB()
{
return $this->numberB;
}
/**
* @param int $numberB
*/
public function setNumberB($numberB)
{
$this->numberB = $numberB;
}
/**
* 这是要被子类覆写的方法
*
* @return int
* @author jiangyi
*/
public function getResult()
{
return 0;
}
}
/**
* 加法实现
*
* Class OperationAdd
*/
class OperationAdd extends Operation
{
public function getResult()
{
return $this->getNumberA() + $this->getNumberB();
}
}
/**
* 减法实现
*
* Class OperationSub
*/
class OperationSub extends Operation
{
public function getResult()
{
return $this->getNumberA() - $this->getNumberB();
}
}
/**
* 乘法实现
*
* Class OperationMul
*/
class OperationMul extends Operation
{
public function getResult()
{
return $this->getNumberA() * $this->getNumberB();
}
}
/**
* 除法实现
*
* Class OperationDiv
*
*/
class OperationDiv extends Operation
{
public function getResult()
{
if ($this->getNumberB() == 0) {
throw new Exception('除数不能为0');
}
return $this->getNumberA() / $this->getNumberB();
}
}
/**
* 工厂类
* 根据相应的运算符new出想要的对象
*
* Class OperationFactory
*/
class OperationFactory
{
/**
* @param $operate
* @return null|OperationAdd|OperationDiv|OperationMul|OperationSub
*/
public static function createOperate($operate)
{
$operateObject = null;
switch ($operate) {
case '+':
$operateObject = new OperationAdd();
break;
case '-':
$operateObject = new OperationSub();
break;
case '*':
$operateObject = new OperationMul();
break;
case '/':
$operateObject = new OperationDiv();
break;
}
return $operateObject;
}
}
$oper = OperationFactory::createOperate('+');
$oper->setNumberA(1);
$oper->setNumberB(4);
$result = $oper->getResult();
echo $result;