不厭其煩

Reder’s Blog, experimental version

Posts Tagged ‘Builder Pattern

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:

Written by Reder

08/31/2009 at 9:58 下午

張貼於Java

Tagged with