【1】什么是抽象工厂模式?
为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类
【2】抽象工厂模式的代码示例:
代码示例:
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class IUser 6 { 7 public: 8 virtual void getUser() = 0; 9 virtual void setUser() = 0; 10 }; 11 12 class SqlUser : public IUser 13 { 14 public: 15 void getUser() 16 { 17 cout << "在sql中返回user" << endl; 18 } 19 void setUser() 20 { 21 cout << "在sql中设置user" << endl; 22 } 23 }; 24 25 class AccessUser : public IUser 26 { 27 public: 28 void getUser() 29 { 30 cout << "在Access中返回user" << endl; 31 } 32 void setUser() 33 { 34 cout << "在Access中设置user" << endl; 35 } 36 }; 37 38 class IDepartment 39 { 40 public: 41 virtual void getDepartment() = 0; 42 virtual void setDepartment() = 0; 43 }; 44 45 class SqlDepartment : public IDepartment 46 { 47 public: 48 void getDepartment() 49 { 50 cout << "在sql中返回Department" << endl; 51 } 52 void setDepartment() 53 { 54 cout << "在sql中设置Department" << endl; 55 } 56 }; 57 58 class AccessDepartment : public IDepartment 59 { 60 public: 61 void getDepartment() 62 { 63 cout << "在Access中返回Department" << endl; 64 } 65 void setDepartment() 66 { 67 cout << "在Access中设置Department" << endl; 68 } 69 }; 70 71 class IFactory 72 { 73 public: 74 virtual IUser *createUser() = 0; 75 virtual IDepartment *createDepartment() = 0; 76 }; 77 78 class SqlFactory : public IFactory 79 { 80 public: 81 IUser *createUser() 82 { 83 return new SqlUser(); 84 } 85 IDepartment *createDepartment() 86 { 87 return new SqlDepartment(); 88 } 89 }; 90 91 class AccessFactory : public IFactory 92 { 93 public: 94 IUser *createUser() 95 { 96 return new AccessUser(); 97 } 98 IDepartment *createDepartment() 99 { 100 return new AccessDepartment(); 101 } 102 }; 103 104 /*************************************************************/ 105 106 class DataAccess 107 { 108 private: 109 static string db; 110 public: 111 static IUser *createUser() 112 { 113 if (db == "access") 114 { 115 return new AccessUser(); 116 } 117 else if (db == "sql") 118 { 119 return new SqlUser(); 120 } 121 } 122 static IDepartment *createDepartment() 123 { 124 if (db == "access") 125 { 126 return new AccessDepartment(); 127 } 128 else if (db == "sql") 129 { 130 return new SqlDepartment(); 131 } 132 } 133 }; 134 135 string DataAccess::db = "sql"; 136 137 /*************************************************************/ 138 139 int main() 140 { 141 IFactory *factory; 142 IUser *user; 143 IDepartment *department; 144 145 factory = new AccessFactory(); 146 user = factory->createUser(); 147 department = factory->createDepartment(); 148 149 user->getUser(); 150 user->setUser(); 151 department->getDepartment(); 152 department->setDepartment(); 153 154 user = DataAccess::createUser(); 155 department = DataAccess::createDepartment(); 156 157 user->getUser(); 158 user->setUser(); 159 department->getDepartment(); 160 department->setDepartment(); 161 162 return 0; 163 }
Good Good Study, Day Day Up.
顺序 选择 循环 总结
原文:http://www.cnblogs.com/Braveliu/p/3946808.html