建造模式

建造模式在构造函数参数过多时提供了一个良好的解决方案,避免了 telescoping constructor pattern 和 javabean 模式的不足。建造模式使得类保持不可变(如 Pizza),从而确保线程安全,同时通过串联 setter 方法提供了易用的构建过程。
摘要由CSDN通过智能技术生成

原文地址:http://leihuang.org/2014/11/09/Builder-Pattern/

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 !


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值