一、工厂模式
工厂模式是对简单工厂模式的优化,以汽车为例,工厂模式有以下角色
- 抽象工厂类:抽象汽车工厂
- 具体工厂类:轿车工厂类、公交工厂类
- 抽象产品类:汽车产品类
- 具体产品类:汽车、公交
各类关系图:
![在这里插入图片描述](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)
二、工厂模式的实现
Factory.h
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
| #ifndef FACTORY_H #define FACTORY_H #include <iostream> #include <string>
using namespace std;
class Products { public: virtual void productMethod() = 0; };
class car : public Products { public: void productMethod() { cout << " car " << endl; } };
class bus : public Products { public: void productMethod() { cout << " bus " << endl; } };
class BaseFactory { public: virtual Products* create() = 0; };
class carFactory : public BaseFactory { public: Products* create() { return new car(); } };
class busFactory : public BaseFactory { public: Products* create() { return new bus(); } };
#endif
|
client.h
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
| #include "Factory.h"
int main() {
BaseFactory* bf = new carFactory(); Products* bp = bf->create(); bp->productMethod(); delete bf; delete bp;
bf = new busFactory(); bp = bf->create(); bp->productMethod();
delete bf; delete bp; return 0; }
|
![在这里插入图片描述](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)
三、unique_ptr的优化
Factory.h
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
| #ifndef FACTORY_H #define FACTORY_H #include <iostream> #include <string> #include <memory> using namespace std;
class Products { public: virtual void productMethod() = 0; };
class car : public Products { public: void productMethod() { cout << " car " << endl; } };
class bus : public Products { public: void productMethod() { cout << " bus " << endl; } };
class BaseFactory { public: virtual unique_ptr<Products> create() = 0; };
class carFactory : public BaseFactory { public: unique_ptr<Products> create() { return unique_ptr<Products>(new car()); } };
class busFactory : public BaseFactory { public: unique_ptr<Products> create() { return unique_ptr<Products>(new bus()); } };
#endif
|
client.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include "Factory.h"
int main() { unique_ptr<BaseFactory> bf(new carFactory()); unique_ptr<Products> bp = bf->create(); bp->productMethod();
bf.reset(new busFactory()); bp = bf->create(); bp->productMethod();
return 0; }
|
![在这里插入图片描述](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)