码迷,mamicode.com
首页 > 其他好文 > 详细

建造模式

时间:2014-11-14 17:53:06      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   io   color   ar   os   sp   java   

原文地址:http://leihuang.net/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 !


建造模式

标签:des   style   http   io   color   ar   os   sp   java   

原文地址:http://blog.csdn.net/speedme/article/details/41120097

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!