一、工厂模式

工厂模式是对简单工厂模式的优化,以汽车为例,工厂模式有以下角色

  • 抽象工厂类:抽象汽车工厂
  • 具体工厂类:轿车工厂类、公交工厂类
  • 抽象产品类:汽车产品类
  • 具体产品类:汽车、公交

各类关系图:
在这里插入图片描述

二、工厂模式的实现

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;
};
//car产品类
class car : public Products
{
public:
void productMethod()
{
cout << " car " << endl;
}
};

//bus产品类
class bus : public Products
{
public:
void productMethod()
{
cout << " bus " << endl;
}
};


//抽象工厂类
class BaseFactory
{
public:
virtual Products* create() = 0;
};

//car工厂类
class carFactory : public BaseFactory
{
public:
Products* create()
{
return new car();
}
};

//bus工厂类
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()
{
/*
使用流程:
1. 需要什么产品
2. 构建对应工厂
3. 使用对应工厂生产对应产品
4. 使用产品对应方法
*/

//生产小轿车
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;
}

在这里插入图片描述


三、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;
};
//car产品类
class car : public Products
{
public:
void productMethod()
{
cout << " car " << endl;
}
};

//bus产品类
class bus : public Products
{
public:
void productMethod()
{
cout << " bus " << endl;
}
};


//抽象工厂类
class BaseFactory
{
public:
virtual unique_ptr<Products> create() = 0;
};

//car工厂类
class carFactory : public BaseFactory
{
public:
unique_ptr<Products> create()
{
return unique_ptr<Products>(new car());
}
};

//bus工厂类
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;
}

在这里插入图片描述