1 ///
2 /// @file Factory.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:27:42
5 ///
6
7 #ifndef __FACTORY_H__
8 #define __FACTORY_H__
9
10
11 #include "Benz.h"
12 #include "Audi.h"
13 #include "Lamborghini.h"
14
15
16 enum Brand
17 {
18 EN_BRAND_CAR_BANZ = 0,
19 EN_BRAND_CAR_AUDI,
20 EN_BRAND_CAR_LAMBORGHINI,
21 };
22
23
24 namespace marrs{
25
26 using std::cout;
27 using std::endl;
28
29 class Factory
30 {
31 public:
32 Car * Produce(int int_brand);
33 void Reclaim(Car * car_brand);
34 };
35
36 }
37
38
39 #endif //__FACTORY_H__
1 ///
2 /// @file Factory.cc
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:39:05
5 ///
6
7 #include "Factory.h"
8
9 namespace marrs{
10
11 Car * Factory::Produce(int int_brand)
12 {
13 switch(int_brand)
14 {
15 case EN_BRAND_CAR_BANZ:
16 return new Benz;
17 case EN_BRAND_CAR_AUDI:
18 return new Audi;
19 case EN_BRAND_CAR_LAMBORGHINI:
20 return new Lamborghini;
21 default:break;
22 }
23 return NULL;
24 }
25
26 void Factory::Reclaim(Car * car_brand)
27 {
28 delete car_brand;
29 }
30
31 }
1 ///
2 /// @file main.cc
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:40:59
5 ///
6
7 #include "Factory.h"
8
9 using namespace marrs;
10
11 int main()
12 {
13 Factory factory;
14
15 Car * car_first = factory.Produce(EN_BRAND_CAR_BANZ);
16 car_first->Run();
17 car_first->Stop();
18 factory.Reclaim(car_first);
19
20 Car * car_second = factory.Produce(EN_BRAND_CAR_AUDI);
21 car_second->Run();
22 car_second->Stop();
23 factory.Reclaim(car_second);
24
25 Car * car_third = factory.Produce(EN_BRAND_CAR_LAMBORGHINI);
26 car_third->Run();
27 car_third->Stop();
28 factory.Reclaim(car_third);
29
30 }
[ccx@ubuntu ~/object-oriented/Factory-Pattern]$>g++ * -o car_factory.exe
[ccx@ubuntu ~/object-oriented/Factory-Pattern]$>./car_factory.exe
Benz is going to running!
Benz is going to stopping!
Audi is going to running!
Audi is going to stopping!
Lamborghini is going to running!
Lamborghini is going to stopping!
1 ///
2 /// @file Factory.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:27:42
5 ///
6
7 #ifndef __FACTORY_H__
8 #define __FACTORY_H__
9
10
11 #include "Car.h"
12
13 namespace marrs{
14
15 using std::cout;
16 using std::endl;
17
18 class Factory
19 {
20 public:
21 virtual ~Factory(){}
22 public:
23 virtual Car * Produce() = 0;
24 void Reclaim(Car * car_brand)
25 {
26 delete car_brand;
27 }
28 };
29
30 }
31
32
33 #endif //__FACTORY_H__
1 ///
2 /// @file Benz_Factory.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 21:21:58
5 ///
6
7 #ifndef __BENZ_FACTORY_H__
8 #defin