首页 > 代码库 > 建造模式

建造模式

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

当构造函数的参数非常多时,并且有多个构造函数时,情况如下:

Pizza(int size) { ... } 
Pizza(int size, boolean cheese) { ... } 
Pizza(int size, boolean cheese, boolean pepperoni) {...} 
Pizza(int size, boolean cheese, boolean pepperoni ,boolean bacon) { ... }

This is called the Telescoping Constructor Pattern. 下面还有一种解决方法叫javabean模式:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

Javabeans make a class mutable even if it is not strictly necessary. So javabeans require an extra effort in handling thread-safety(an immutable class is always thread safety!).详见:JavaBean Pattern

下面介绍一种更好的方法,就是今天的主题:建造模式

 private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

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

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

注意到现在Pizza是一个immutable class,所以它是线程安全的。又因为每一个Builder‘s setter方法都返回一个Builder对象,所以可以串联起来调用。如下

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

2014-11-09 18:21:17

Brave,Happy,Thanksgiving !


建造模式