生成器模式是一种在生成过程相同的情况下隐藏实现细节的创建型模式。
可以考虑这种场景,一个阅读器需要将一个文本转换为其他格式,转换的过程是相同的,比如先转换文字,再转换图片,段落,字体,染色等,最后组合在一起,得到创建的结果。再比如房屋的建造,都是先选地盘,然后挖地基,运输材料,画图纸,然后盖楼,不同的楼会选择不同的地盘,挖不同深度的地基等,然后建成的房屋也有不同的用途。
和抽象工厂模式不同,生成器模式是过程相同的,创建完之后直接返回一个创建好的对象,抽象工厂是先拿出来一个组件,然后选择用里面的哪些部件,最后拼凑起来。
书中例子的uml图如下所示(书中还有一个TextWigetConverter,这里省略了)
代码实现:
1 /********************************
2 * design pattern of GOF : Builder
3 * Author: shapherd
4 * data: 2010-11-19
5 * ******************************/
6 #include<iostream>
7 #include<string>
8 using namespace std;
9
10 /// product
11 class ASCIIText{
12 public:
13 ASCIIText(string showstring)
14 {
15 _showstring = showstring;
16 }
17 void show()
18 {
19 cout<<_showstring<<" has convert to ASCIIText"<<endl;
20 }
21 private:
22 string _showstring;
23 };
24 class TeXText{
25 public:
26 TeXText(string charstring, string fontstring)
27 {
28 _charstring = charstring;
29 _fontstring = fontstring;
30 }
31 void show()
32 {
33 cout<<_charstring<<" has convert to TeX chars" <<endl;
34 cout<<_fontstring<<" has convert to TeX font" <<endl;
35 cout<<"has convert to TeX paragraph" <<endl;
36 }
37 private:
38 string _charstring;
39 string _fontstring;
40 };
41
42 //Builder
43 class TextConverter {
44 public:
45 virtual void ConvertCharacter(string charstring){}
46 virtual void ConvertFontChange(string fontstring){}
47 virtual void ConvertParagraph(){}
48 virtual ~TextConverter() = 0;
49 };
50 TextConverter::~TextConverter(){}
51 //ConcreteBuilder
52 class ASCIIConverter : public TextConverter{
53 public:
54 void ConvertCharacter(string charstring)
55 {
56 _charstring = charstring;
57 }
58 ASCIIText* GetASCIIText()
59 {
60 return new ASCIIText(_charstring);
61 }
62 private:
63 string _charstring;
64 };
65 class TeXConverter : public TextConverter{
66 public:
67 void ConvertCharacter(string charstring)
68 {
69 _charstring = charstring;
70 }
71 void ConvertFontChange(string fontstring)
72 {
73 _fontstring = fontstring;
74 }
75 TeXText* GetTeXText()
76 {
77 return new TeXText(_charstring, _fontstring);
78 }
79 private:
80 string _charstring;
81 string _fontstring;
82 };
83
84 //Director
85 class RTFReader {
86 public:
87 RTFReader(TextConverter* ptc)
88 {
89 ptc->ConvertCharacter("hahahachar");
90 ptc->ConvertFontChange("hahahaFont");
91 ptc->ConvertParagraph();
92 }
93 };
94
95 //main
96 int main(int argc, char** argv)
97 {
98 ASCIIConverter* pac = new ASCIIConverter;
99 RTFReader ASCIIReader(pac);
100 ASCIIText* pat = pac->GetASCIIText();
101 pat->show();
102 delete pac;
103 delete pat;
104
105 TeXConverter* ptc = new TeXConverter;
106 RTFReader TeXReader(ptc);
107 TeXText* ptt = ptc->GetTeXText();
108 ptt->show();
109 delete ptc;
110 delete ptt;
111
112 return 0;
113 }
114
运行结果: