设计模式(三)

本文总阅读量

抽象工厂模式

工厂方法模式UML类图

我感觉就是工厂方法的增强版,多了更多的操作子类,随之而来的就是更多的抽象工厂子类。每个工厂子类都可以操作对应的操作子类。并且它们使用的是统一的接口。

只需要在客户端更换抽象工厂子类,即可实现不同的操作。

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
/*
* AbstractFactory.cpp
* 抽象工厂模式
* Created on: 2016年3月11日
* Author: Administrator
*/


#include <iostream>
using namespace std;

class User {
private:
int id;
string name;
public:

int getId() const {
return id;
}

void setId(int id) {
this->id = id;
}

const string& getName() const {
return name;
}

void setName(const string& name) {
this->name = name;
}
};

class IUser {
public:

virtual void Insert(User *user) {
}
virtual void GetUser(int id) {

}
};

class SqlserverUser: public IUser {
public:

void Insert(User *user) {
cout << "在SQL server中给user表增加了一条数据" << endl;
}
void GetUser(int id) {
cout << "在SQL server中根据ID得到user表一条数据" << endl;

}
};
class AcessUser: public IUser {
public:

void Insert(User *user) {
cout << "在Acess中给user表增加了一条数据" << endl;
}
void GetUser(int id) {
cout << "在Acess中根据ID得到user表一条数据" << endl;
}
};

class Department {

};

class IDepartment {
public:

virtual void Insert(Department *deparment) {
}
virtual void GetDepartment(int id) {
}
};
class SqlserverDepartment: public IDepartment {
public:

void Insert(Department *deparment) {
cout << "在SQL server中给Department表增加了一条数据" << endl;
}
void GetDepartment(int id) {
cout << "在SQL server中根据ID得到Department表一条数据" << endl;
}
};

class AcessDepartment: public IDepartment {
public:

void Insert(Department *deparment) {
cout << "在Acess中给Department表增加了一条数据" << endl;
}
void GetDepartment(int id) {
cout << "在Acess中根据ID得到Department表一条数据" << endl;
}
};

class IFactory {
public:

virtual IUser * CreateUser() {
}
virtual IDepartment * CreateDepartment() {
}
};
class SqlserverFactory: public IFactory {
public:

IUser * CreateUser() {
return new SqlserverUser();
}
IDepartment * CreateDepartment() {
return new SqlserverDepartment();
}
};

class AcessFactory: public IFactory {
public:

IUser * CreateUser() {
return new AcessUser();
}
IDepartment * CreateDepartment() {
return new AcessDepartment();
}
};

int main(void) {
cout << "helloFactory" << endl;

User *user = new User();
Department *dep = new Department();
//在这里传入不同使用的数据库,来实现用不同数据库进行不同的操作。
IFactory *factory = new AcessFactory();
//IFactory *factory = new SqlserverFactory();

IUser *iuser = factory->CreateUser();

IDepartment *idep = factory->CreateDepartment();

iuser->Insert(user);
iuser->GetUser(1);
idep->Insert(dep);
idep->GetDepartment(1);

return 0;
}