简单工厂模式

 1 #ifndef SIMPLE_FACTORY_H
 2 #define SIMPLE_FACTORY_H
 3 
 4 #include <iostream>
 5 
 6 class Product
 7 {
 8 public:
 9     virtual void play(void) = 0;    // 没有定义的函数记得声明为纯虚函数
10 };
11 
12 class DVD: public Product
13 {
14 public:
15     void play(void)
16     {
17         std::cout << "now play DVD" << std::endl;
18     }
19 };
20 
21 class CD: public Product
22 {
23 public:
24     void play(void)
25     {
26         std::cout << "now play CD" << std::endl;
27     }
28 };
29 
30 class Creator
31 {
32 public:
33     enum PRODUCT_TYPE
34     {
35         TYPE_DVD,
36         TYPE_CD
37     };
38 
39     Product* factory(PRODUCT_TYPE type) {
40         switch (type) {
41         case TYPE_DVD:
42             return new DVD;
43         case TYPE_CD:
44             return new CD;
45         default:
46             return NULL;
47         }
48     }
49 };
50 
51 #endif // SIMPLE_FACTORY_H

下面是使用的代码

 1 #include "SimpleFactory.h"
 2 
 3 int main(void)
 4 {
 5     Creator creator;
 6     Product* dvd = creator.factory(Creator::TYPE_DVD);
 7     Product* cd = creator.factory(Creator::TYPE_CD);
 8 
 9     dvd->play();
10     cd->play();
11 
12     return 0;
13 }

输出为

now play DVD
now play CD

 

posted @ 2013-11-04 17:45  WendellYih  阅读(183)  评论(0编辑  收藏  举报