设为首页 加入收藏

TOP

设计模式学习——工厂模式(Factory Pattern)(三)
2017-10-10 12:35:42 】 浏览:7622
Tags:设计模式 学习 工厂 模式 Factory Pattern
e
__BENZ_FACTORY_H__ 9 10 #include "Factory.h" 11 #include "Benz.h" 12 13 namespace marrs{ 14 15 class BenzFactory 16 : public Factory 17 { 18 public: 19 Car * Produce() 20 { 21 return new Benz; 22 } 23 }; 24 25 } 26 27 #endif // __BENZ_FACTORY_H__
 1  ///
 2  /// @file    Audi_Factory.h
 3  /// @author  marrs(chenchengxi993@gmail.com)
 4  /// @date    2017-08-12 21:21:58
 5  ///
 6 
 7 #ifndef __AUDI_FACTORY_H__
 8 #define __AUDI_FACTORY_H__
 9 
10 #include "Factory.h"
11 #include "Audi.h"
12 
13 namespace marrs{
14 
15 class AudiFactory
16 : public Factory
17 {
18     public:
19         Car * Produce()
20         {
21             return new Audi;
22         }
23 };
24 
25 }
26 
27 #endif // __AUDI_FACTORY_H__
 1  ///
 2  /// @file    Lamborghini_Factory.h
 3  /// @author  marrs(chenchengxi993@gmail.com)
 4  /// @date    2017-08-12 21:21:58
 5  ///
 6 
 7 #ifndef __LAMBORGHINI_FACTORY_H__
 8 #define __LAMBORGHINI_FACTORY_H__
 9 
10 #include "Factory.h"
11 #include "Lamborghini.h"
12 
13 namespace marrs{
14 
15 class LamborghiniFactory
16 : public Factory
17 {
18     public:
19         Car * Produce()
20         {
21             return new Lamborghini;
22         }
23 };
24 
25 }
26 
27 #endif // __LAMBORGHINI_FACTORY_H__

 

 

最后修改main.cc

 1  ///
 2  /// @file    main.cc
 3  /// @author  marrs(chenchengxi993@gmail.com)
 4  /// @date    2017-08-12 20:40:59
 5  ///
 6  
 7 #include "Benz_Factory.h"
 8 #include "Audi_Factory.h"
 9 #include "Lamborghini_Factory.h"
10 
11 using namespace marrs;
12 
13 void BenzAction()
14 {
15     Factory * factory = new BenzFactory;
16     Car * car_first = factory->Produce(); 
17     car_first->Run();
18     car_first->Stop();
19     factory->Reclaim(car_first);
20     delete factory;
21 }
22 
23 void AudiAction()
24 {
25     Factory * factory = new AudiFactory;
26     Car * car_first = factory->Produce(); 
27     car_first->Run();
28     car_first->Stop();
29     factory->Reclaim(car_first);
30     delete factory;
31 }
32 
33 void LamborghiniAction()
34 {
35     Factory * factory = new LamborghiniFactory;
36     Car * car_first = factory->Produce(); 
37     car_first->Run();
38     car_first->Stop();
39     factory->Reclaim(car_first);
40     delete factory;
41 }
42 
43 
44 int main()
45 {
46     BenzAction();
47     AudiAction();
48     LamborghiniAction();
49 
50     return 0;
51 }

 

 

编译,运行

[ccx@ubuntu ~/object-oriented/Factory-Pattern_2]$>g++ * -o car_Factory.exe
[ccx@ubuntu ~/object-oriented/Factory-Pattern_2]$>./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 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇MVC与MVVM设计模式理解 下一篇简单谈谈面向对象和面向过程的区别

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目