`
阅读更多

The goal of builder is to separate the construction from the “representation,” to allow multiple different representations . The construction process stays the same, but the resulting object has different possible representations.GoF points out that the main difference with Abstract Factory is that a Builder creates the object step-by-step, so the fact that the creation process is spread out in time seems to be important. In addition, it seems that the “director” gets a stream of pieces that it passes to the Builder, and each piece is used to perform one of the steps in the build process.

......

Here’s an example that may be a little more compelling, or at least give more of an idea of what Builder is trying to do. Media may be constructed into different representations, in this case books, magazines and web sites. The example argues that the steps involved are the same, and so can be abstracted into the director class.

//: builder:BuildMedia.java

// Example of the Builder pattern

package builder;

import java.util.*;

import junit.framework.*;

 

// Different "representations" of media:

class Media extends ArrayList {}

class Book extends Media {}

class Magazine extends Media {}

class WebSite extends Media {}

 

// ... contain different kinds of media items:

class MediaItem {

  private String s;

  public MediaItem(String s) { this.s = s; }

  public String toString() { return s; }

}

class Chapter extends MediaItem {

  public Chapter(String s) { super(s); }

}

class Article extends MediaItem {

  public Article(String s) { super(s); }

}

class WebItem extends MediaItem {

  public WebItem(String s) { super(s); }

}

 

// ... but use the same basic construction steps:

class MediaBuilder {

  public void buildBase() {}

  public void addMediaItem(MediaItem item) {}

  public Media getFinishedMedia() { return null; }

}

 

class BookBuilder extends MediaBuilder {

  private Book b;

  public void buildBase() {

    System.out.println("Building book framework");

    b = new Book();

  }

  public void addMediaItem(MediaItem chapter) {

    System.out.println("Adding chapter " + chapter);

    b.add(chapter);

  }

  public Media getFinishedMedia() { return b; }

 

class MagazineBuilder extends MediaBuilder {

  private Magazine m;

  public void buildBase() {

    System.out.println("Building magazine framework");

    m = new Magazine();

  }

  public void addMediaItem(MediaItem article) {

    System.out.println("Adding article " + article);

    m.add(article);

  }

  public Media getFinishedMedia() { return m; }

 

class WebSiteBuilder extends MediaBuilder {

  private WebSite w;

  public void buildBase() {

    System.out.println("Building web site framework");

    w = new WebSite();

  }

  public void addMediaItem(MediaItem webItem) {

    System.out.println("Adding web item " + webItem);

    w.add(webItem);

  }

  public Media getFinishedMedia() { return w; }

 

class MediaDirector { // a.k.a. "Context"

  private MediaBuilder mb;

  public MediaDirector(MediaBuilder mb) {

    this.mb = mb; // Strategy-ish

  }

  public Media produceMedia(List input) {

    mb.buildBase();

    for(Iterator it = input.iterator(); it.hasNext();)

      mb.addMediaItem((MediaItem)it.next());

    return mb.getFinishedMedia();

  }

};

 

public class BuildMedia extends TestCase {

  private List input = Arrays.asList(new MediaItem[] {

    new MediaItem("item1"), new MediaItem("item2"),

    new MediaItem("item3"), new MediaItem("item4"),

  });

  public void testBook() {

    MediaDirector buildBook =

      new MediaDirector(new BookBuilder());

    Media book = buildBook.produceMedia(input);

    String result = "book: " + book;

    System.out.println(result);

    assertEquals(result,

      "book: [item1, item2, item3, item4]");

  }

  public void testMagazine() {

    MediaDirector buildMagazine =

      new MediaDirector(new MagazineBuilder());

    Media magazine = buildMagazine.produceMedia(input);

    String result = "magazine: " + magazine;

    System.out.println(result);

    assertEquals(result,

      "magazine: [item1, item2, item3, item4]");

  }

  public void testWebSite() {

    MediaDirector buildWebSite =

      new MediaDirector(new WebSiteBuilder());

    Media webSite = buildWebSite.produceMedia(input);

    String result = "web site: " + webSite;

    System.out.println(result);

    assertEquals(result,

      "web site: [item1, item2, item3, item4]");

  }

  public static void main(String[] args) {

    junit.textui.TestRunner.run(BuildMedia.class);

  }

} ///:~

 

Note that in some ways this could be seen as a more complicated State pattern, since the behavior of the director depends on what type of builder you use. Instead of simply forwarding the requests through to the underlying State object, however, the director has a sequence of operations to perform, and it uses the State object as a Policy to fulfill its job. Thus, Builder could be described as using a Policy to create objects.

 

//示例代码是比较简单的,能够很好地读懂,但是没有具体的应用实例,不是很好理解。看来具体的项目时间还是比较重要啊!整体的感觉是:Builder模式是按照自己的喜好组装好自己的目标对象,Abstract Factory模式则是一步到位得到自己的目标对象 。找了一个很有意思的讲解:builder 与abstract factory 之间的区别

实际的样例,等以后有了实际的项目经验就好了,到时再整理咯!

 

 

分享到:
评论

相关推荐

    Laravel开发-form-builder

    $form = $formBuilder->create('App\Http\Requests\MyFormRequest', [ 'method' => 'POST', 'url' => route('my-route'), ]); $form->add('name', 'text', [ 'rules' => 'required|min:3|max:255', 'attr' =...

    electron 使用 electron-builder 打包所需工具 winCodeSign-2.6.0.zip

    `Electron Builder` 是一个完整的解决方案,用于构建、打包和发布 Electron 应用程序,支持多种操作系统,包括 Windows、macOS 和 Linux。在本文中,我们将深入探讨 `Electron` 和 `Electron Builder`,以及它们如何...

    electron-builder.rar

    《Electron Builder:构建Windows 10应用的利器》 Electron Builder,作为一个强大的工具,是Electron应用程序打包和发布的首选方案。它专为开发者设计,尤其针对那些在中国网络环境不佳的情况下,仍需确保顺利构建...

    前端开源库-swint-builder-css.zip

    10. **文档齐全**:Swint-Builder-CSS 提供详尽的文档和示例,帮助开发者快速上手并了解其工作原理。 在实际项目中,通过Swint-Builder-CSS,开发者可以专注于编写可读性强、结构清晰的CSS代码,而不必担心编译、...

    泛微OAE10,E-Builder零代码应用构建平台操作手册

    ### 泛微OAE10,E-Builder零代码应用构建平台操作手册 #### eBuilder零代码平台简介 eBuilder作为一款先进的零代码应用构建平台,是泛微OA系统中的一个重要组成部分。该平台允许用户无需编写任何代码即可快速构建出...

    Python库 | django-forms-builder-0.4.7.tar.gz

    10. **安装与集成**:要在你的Django项目中使用`django-forms-builder`,你需要先解压`django-forms-builder-0.4.7.tar.gz`,然后按照文档指示安装和配置,将其添加到你的`INSTALLED_APPS`列表中,并运行数据库迁移...

    Laravel开发-laravel-api-query-builder

    $users = $queryBuilder->paginate(10); ``` #### 3.5 关联模型 如果你需要处理一对多或多对多的关系,`laravel-api-query-builder`也提供了方便的方法: ```php $queryBuilder->with('posts'); ``` ### 4. ...

    vim-builder-2018-10-22.tar

    vim-builder-2018-10-22.tar

    Laravel开发-formbuilder

    ### 10. 表单重定向 完成表单操作后,通常会根据情况重定向用户。使用 `redirect()` 函数可以实现这一点: ```php return redirect('success-page'); ``` 总结,Laravel 的 FormBuilder 为开发者提供了一种简洁、...

    Skin-builder 6.0

    10. **文件管理**:在“builder”这个压缩包文件中,可能包含了Skin-builder 6.0的主程序、必要的库文件、帮助文档以及可能的示例皮肤文件,用户解压后即可开始使用。 通过以上知识点,我们可以了解到Skin-builder ...

    Android代码-android-ab-test-builder

    // Show button RED : GREEN : YELLOW = 80 : 10 : 10 final ABTest buttonColorABTest = new ABTest.Builder(this) .with("ButtonColorPatterns", ButtonColorPatterns.class) .addPattern(new ABPattern...

    E10低代码平台E-Builder简介.pptx

    E10低代码平台E-Builder简介.pptx

    antd-react-form-builder:例子

    antd-react-form-builder Deprecated,请使用 之所以写了这个项目有以下几点原因: 的表单验证是会触发整个组件渲染,(使用Form.create()装饰器后和getFieldDecorator...兼容IE10以上,兼容谷歌、Safari、火狐等浏览器

    cellulose-builder

    User-friendly toolkit for building (PDB format) cellulose crystalline strucures. 源代码:https://code.google.com/archive/p/cellulose-builder/,如条件允许请前往此官网下载 ... DOI: 10.1002/jcc.22959

    Laravel开发-builder

    在Laravel框架中,Builder是Eloquent ORM(对象关系映射)系统的核心组成部分,它提供了...通过`builder-master`这个压缩包文件,你可能可以找到更详细的示例代码和实践,进一步了解和学习Laravel Builder的具体应用。

    7-CPP-Builder.zip

    10. **第三方库支持**:C++ Builder社区提供了大量的第三方组件和库,可以扩展IDE的功能,满足各种项目需求。 在《C++ Builder编程指南》中,读者可以深入学习如何使用C++ Builder进行程序设计,包括UI设计、事件...

    depth-dataset-builder-master.rar

    这个压缩包“depth-dataset-builder-master.rar”包含了源代码,允许用户自定义地生成针对特定任务的深度图像数据。 深度数据集在机器学习,特别是深度学习中扮演着至关重要的角色。它们提供了场景的三维信息,这...

    前端开源库-hot-builder-cg.zip

    "前端开源库-hot-builder-cg.zip" 是一个包含前端开发工具和库的压缩包,它可能为开发者提供了一种高效构建、热加载和持续集成的解决方案。虽然没有具体的标签给出,我们可以从文件名推测,这个库可能专注于"hot ...

Global site tag (gtag.js) - Google Analytics