抽象工厂模式

 1 #ifndef ABSTRACTFACTORY_H
 2 #define ABSTRACTFACTORY_H
 3 
 4 #include <iostream>
 5 
 6 class AbstractDisk
 7 {
 8 public:
 9     virtual void play(void) = 0;
10 };
11 
12 class AbstractFactory
13 {
14 public:
15     virtual AbstractDisk* create(void) = 0;
16 };
17 
18 class DiskDVD: public AbstractDisk
19 {
20 public:
21     void play(void)
22     {
23         std::cout << "now play DVD" << std::endl;
24     }
25 };
26 
27 class DiskCD: public AbstractDisk
28 {
29 public:
30     void play(void)
31     {
32         std::cout << "now play CD" << std::endl;
33     }
34 };
35 
36 class DVDFactory: public AbstractFactory
37 {
38 public:
39     AbstractDisk* create(void)
40     {
41         return new DiskDVD;
42     }
43 };
44 
45 class CDFactory: public AbstractFactory
46 {
47 public:
48     AbstractDisk* create(void)
49     {
50         return new DiskCD;
51     }
52 };
53 
54 #endif // ABSTRACTFACTORY_H

客户端代码

 1 #include "AbstractFactory.h"
 2 
 3 int main(void)
 4 {
 5     DVDFactory dvdFactory;
 6     CDFactory cdFactory;
 7     AbstractDisk *Dvd = dvdFactory.create();
 8     AbstractDisk *Cd = cdFactory.create();
 9 
10     Dvd->play();
11     Cd->play();
12 
13     return 0;
14 }

 

posted @ 2013-11-04 22:08  WendellYih  阅读(174)  评论(0编辑  收藏  举报