来自于《大话设计模式》
抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
UML 类图:
代码实现 C++:
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class IUser
6 {
7 public:
8 virtual void insert(const string& s) = 0;
9 virtual string getUser(int id) = 0;
10 };
11
12 class SqlserverUser : public IUser
13 {
14 public:
15 virtual void insert(const string& s)
16 {
17 cout << "SqlserverUser::insert " << s << endl;
18 }
19 virtual string getUser(int id)
20 {
21 cout << "SqlserverUser::getUser " << id << endl;
22 return "";
23 }
24 };
25
26 class AccessUser : public IUser
27 {
28 public:
29 virtual void insert(const string& s)
30 {
31 cout << "AccessUser::insert " << s << endl;
32 }
33 virtual string getUser(int id)
34 {
35 cout << "AccessUser::getUser " << id << endl;
36 return "";
37 }
38 };
39
40 class IDepartment
41 {
42 public:
43 virtual void insert(const string& s) = 0;
44 virtual string getDepartment(int id) = 0;
45 };
46
47 class SqlserverDepartment : public IDepartment
48 {
49 public:
50 virtual void insert(const string& s)
51 {
52 cout << "SqlserverDepartment::insert " << s << endl;
53 }
54 virtual string getDepartment(int id)
55 {
56 cout << "SqlserverDepartment::getDepartment " << id << endl;
57 return "";
58 }
59 };
60
61 class AccessDepartment : public IDepartment
62 {
63 public:
64 virtual void insert(const string& s)
65 {
66 cout << "AccessDepartment::insert " << s << endl;
67 }
68 virtual string getDepartment(int id)
69 {
70 cout << "AccessDepartment::getDepartment " << id << endl;
71 return "";
72 }
73 };
74
75 class IFactory
76 {
77 public:
78 virtual IUser * CreateUser() = 0;
79 virtual IDepartment * CreateDepartment() = 0;
80 };
81
82 class SqlserverFactory : public IFactory
83 {
84 public:
85 virtual IUser * CreateUser()
86 {
87 return new SqlserverUser;
88 }
89 virtual IDepartment* CreateDepartment()
90 {
91 return new SqlserverDepartment;
92 }
93 };
94
95 class AccessFactory : public IFactory
96 {
97 public:
98 virtual IUser * CreateUser()
99 {
100 return new AccessUser;
101 }
102 virtual IDepartment * CreateDepartment()
103 {
104 return new AccessDepartment;
105 }
106 };
107
108 int main()
109 {
110 string user = "abc";
111 string department = "xyz";
112
113 IFactory * factory = new AccessFactory;
114 IUser * iu = factory->CreateUser();
115 iu->insert(user);
116 iu->getUser(1);
117 IDepartment * id = factory->CreateDepartment();
118 id->insert(department);
119 id->getDepartment(1);
120 delete factory;
121 delete iu;
122 delete id;
123
124 factory = new SqlserverFactory;
125 iu = factory->CreateUser();
126 iu->insert(user);
127 iu->getUser(1);
128 id = factory->CreateDepartment();
129 id->insert(department);
130 id->getDepartment(1);
131 delete factory;
132 delete iu;
133 delete id;
134
135 return 0;
136 }
posted on 2011-04-27 14:53
unixfy 阅读(504)
评论(0) 编辑 收藏 引用