随笔-167  评论-8  文章-0  trackbacks-0
The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes".
class diagram
uml diagram



 1 /* GUIFactory example */
 2  
 3 #include <iostream>
 4  
 5 class Button {
 6 public:
 7     virtual void paint() = 0;
 8     virtual ~Button() { }
 9 };
10  
11 class WinButton : public Button {
12 public:
13     void paint() {
14         std::cout << "I'm a WinButton";
15     }
16 };
17  
18 class OSXButton : public Button {
19 public:
20     void paint() {
21         std::cout << "I'm an OSXButton";
22     }
23 };
24  
25 class GUIFactory {
26 public:
27     virtual Button* createButton() = 0;
28     virtual ~GUIFactory() { }
29 };
30  
31 class WinFactory : public GUIFactory {
32 public:
33     Button* createButton() {
34         return new WinButton();
35     }
36  
37     ~WinFactory() { }
38 };
39  
40 class OSXFactory : public GUIFactory {
41 public:
42     Button* createButton() {
43         return new OSXButton();
44     }
45  
46     ~OSXFactory() { }
47 };
48  
49 class Application {
50 public:
51     Application(GUIFactory* factory) {
52         Button* button = factory->createButton();
53         button->paint();
54         delete button;
55         delete factory;
56     }
57 };
58  
59 GUIFactory* createOsSpecificFactory() {
60     int sys;
61     std::cout "\nEnter OS type (0: Windows, 1: MacOS X): ";
62     std::cin >> sys;
63  
64     if (sys == 0) {
65         return new WinFactory();
66     } else {
67         return new OSXFactory();
68     }
69 }
70  
71 int main() {
72     Application application(createOsSpecificFactory());
73 }
74 
posted on 2012-11-13 16:46 老马驿站 阅读(358) 评论(0)  编辑 收藏 引用 所属分类: Design pattern