子弹 の VISIONS

NEVER back down ~~

C++博客 首页 新随笔 联系 聚合 管理
  112 Posts :: 34 Stories :: 99 Comments :: 0 Trackbacks

Only some thinking to help to think about the Builder Pattern, but it's not so intuitive.
Suppose that we want to save data to files.

class File { /*abstract file*/ };
class FileBuilder
{
public:
    virtual bool buildFileHeader() =0;
    virtual bool buildFileBody()   =0;
    virtual bool buildFileTail()   =0;
    virtual File* getFile()        =0;
};
 
class BmpFile  : public File { .... };
class GifFile  : public File { .... };
class JpegFile : public File { .... };
//other kinds of files
 
class BmpFileBuilder : public FileBuilder
{
};
 
class GifFileBuilder : public FileBuilder
{
};
 
class JpegFileBuilder : public FileBuilder
{
};
//builders above implement those interfaces from FileBuilder
//other kinds of file builders

 
//usage
File* buildFile(FileBuilder* fb)
{
    fb.buildFileHeader();
    fb.buildFileBody();
    fb.buildFileTail();
    return fb.GetFile();
}
void func()
{
    FileBuilder* fb = new SomeFileBuilder();
    File* f = buildFile(fb);
    //use f
    ....
}
 
Key Points:
1. Each builder is responsible for its buildXXX()
2. Each builder builds one kind of File
3. the File would be created in builder's constructor

posted on 2008-08-08 09:45 子弹のVISIONS 阅读(703) 评论(0)  编辑 收藏 引用 所属分类: 1.2 闲人杂语

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理