工厂方法模式
和简单工厂的不同之处:
把逻辑判断从工厂类中移到客户端。
工厂类下多了几个子类用来创建对应的进行实际操作的
子类对象。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/*
* FactoryMethod.cpp
*
* 工厂方法模式
* Created on: 2016年3月13日 下午8:56:50
* Author: Wayne 13186259527@163.com
*/
#include <iostream>
#include <stdlib.h>
using namespace std;
class Operation {
private:
double x, y;
char c;
public:
Operation() {
}
Operation(double x, double y, char c) {
this->x = x;
this->y = y;
this->c = c;
}
virtual double Calc(double x, double y) {
return 0;
}
;
double GetX() {
return this->x;
}
double GetY() {
return this->y;
}
char GetC() {
return this->c;
}
};
class Add: public Operation {
public:
Add() {
}
;
double Calc(double x, double y) {
return x + y;
}
};
class Sub: public Operation {
public:
Sub() {
}
;
double Calc(double x, double y) {
return x - y;
}
};
class Mul: public Operation {
public:
Mul() {
}
;
;
double Calc(double x, double y) {
return x * y;
}
};
class Div: public Operation {
public:
Div() {
}
;
double Calc(double x, double y) {
if (y == 0) {
cout << "0不能作为被除数" << endl;
exit(0);
}
return x / y;
}
};
class Factory {
public:
virtual Operation* CreateOperation() {
return NULL;
}
;
};
class AddFactory: public Factory {
public:
Operation* CreateOperation() {
return new Add();
}
};
class SubFactory: public Factory {
public:
Operation* CreateOperation() {
return new Sub();
}
};
class MulFactory: public Factory {
public:
Operation* CreateOperation() {
return new Mul();
}
};
class DivFactory: public Factory {
public:
Operation* CreateOperation() {
return new Div();
}
};
int main(void) {
cout << "hello world" << endl;
cout << "eg:5+8" << endl;
double x, y;
char c;
cin >> x >> c >> y;
double result;
Factory *f = NULL;//指向对应的工厂
Operation *p = NULL;//指向对应的实现方法的子类
switch (c) {
case '+':
f = new AddFactory();
break;
case '-':
f = new SubFactory();
break;
case '*':
f = new MulFactory();
break;
case '/':
f = new DivFactory();
break;
}
p = f->CreateOperation();
result = p->Calc(x, y);
cout << "result = " << result << endl;
return 0;
}