forked from hulin32/design-patterns-by-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactoryMethod.php
More file actions
116 lines (100 loc) · 1.65 KB
/
FactoryMethod.php
File metadata and controls
116 lines (100 loc) · 1.65 KB
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
<?php
////////////////////////////////
// from Operation.php
class Operation
{
protected $a = 0;
protected $b = 0;
public function setA($a)
{
$this->a = $a;
}
public function setB($b)
{
$this->b = $b;
}
public function getResult()
{
$result = 0;
return $result;
}
}
/**
* add
*/
class OperationAdd extends Operation
{
public function getResult()
{
return $this->a + $this->b;
}
}
/**
* Mul
*/
class OperationMul extends Operation
{
public function getResult()
{
return $this->a * $this->b;
}
}
/**
* sub
*/
class OperationSub extends Operation
{
public function getResult()
{
return $this->a - $this->b;
}
}
/**
* div
*/
class OperationDiv extends Operation
{
public function getResult()
{
$this->a / $this->b;
}
}
//////////////////////////////////////
interface IFactory
{
public function CreateOperation();
}
class AddFactory implements IFactory
{
public function CreateOperation()
{
return new OperationAdd();
}
}
class SubFactory implements IFactory
{
public function CreateOperation()
{
return new OperationSub();
}
}
class MulFactory implements IFactory
{
public function CreateOperation()
{
return new OperationMul();
}
}
class DivFactory implements IFactory
{
public function CreateOperation()
{
return new OperationDiv();
}
}
//客户端代码
$operationFactory = new AddFactory();
$operation = $operationFactory->CreateOperation();
$operation->setA(10);
$operation->setB(10);
echo $operation->getResult()."\n";