不厭其煩

Reder’s Blog, experimental version

Builder Pattern

with 2 comments

什麼是 Builder Pattern?

Builder Pattern 是 Joshua Bloch 在 JavaOne 2007 的演講中提出的:利用在一個 class 中內置的 public static class Builder ,並將原先的 constructor 封裝在該 class 中,我們可以免除以下問題:

  • Ugly constructor. 例如:new NutritionFacts(int servingSize, int servings,
    int calories, int fat, int 15 more optional params!);
  • Constructor telescoping. 如果是上例的 constructor ,我們在使用的時候一定得參看原先的 constructor 說明,才能知道各個參數的意義。如:NutritionFacts locoCola =
    new NutritionFacts(240, 8, 0, 0, 30, 28);
    ,不看的話根本不知道那一串數字是什麼東西。
  • Too many setters required when creating objects. 如果不用像上例的方式,改用 Java Bean style setters 呢?因為沒有辦法強制必須要什麼參數設定了才能產生出一個新的 instance ,所以造成了不確定性和異變性。

Builder Pattern: 一個範例

例如我們有個 User 的 Java Bean ,其中 idusername 為必須。我們加上了一個 Builder 如下 。

public class User {
  private long id;
  private String username;
  private String firstname;
  private String lastname;
  private String email;

  public static class Builder {
    private long id;
    private String username;
    private String firstname;
    private String lastname;
    private String email;

    public Builder(long id, String username) {
      this.id = id;
      this.username = username;
      return this;
    }

    public Builder firstname(String firstname) {
      this.firstname = firstname;
      return this;
    }

    public Builder lastname(String lastname) {
      this.lastname = lastname;
      return this;
    }

    public Builder email(String email) {
      this.email = email;
      return this;
    }

    public User build() {
        return new User(this);
    }
  }

  private User(Builder builder) {
    this.id = builder.id;
    this.username = builder.username;
    this.firstname = builder.firstname;
    this.lastname = builder.lastname;
    this.email = builder.email;
  }
}

而我們就可以用下列的方式建立一個新的 User

public class UserCreator {
  public static void main(String[] args) {

    User user = new User.Builder(541, "jsmith").email("john@smith.com").build();

  }
}

但其實 Builder 的建立相當累人,是一堆重複性的 code 。不過我們有現成的 Eclipse Builder plugin 可以使用,幫助我們快速建立 Builder 。

More:

Advertisements

Written by Reder

08/31/2009 於 9:58 下午

張貼於Java

Tagged with

2 回應

Subscribe to comments with RSS.

  1. […] Reder 寫作的:”什麼是 Builder Pattern?” 一文。Wiki 上也有 Builder […]

  2. What i do not realize is in reality how you are not really much more well-liked than you
    might be now. You are so intelligent. You already know thus
    significantly with regards to this subject, made me in my opinion consider it
    from a lot of various angles. Its like women and men are not interested until
    it is one thing to do with Lady gaga! Your own stuffs excellent.

    All the time maintain it up!


發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

%d 位部落客按了讚: