程序员人生 网站导航

设计模式:建造模式

栏目:框架设计时间:2015-01-14 09:11:50

原文地址:http://leihuang.org/2014/12/03/builder/

Creational 模式

物件的产生需要消耗系统资源,所以如何有效力的产生、管理 与操作物件,1直都是值得讨论的课题, Creational 模式即与物件的建立相干,在这个分类下的模式给出了1些指点原则及设计的方向。下面罗列到的全属于Creational 模式

  • Simple Factory 模式
  • Abstract Factory 模式
  • Builder 模式
  • Factory Method 模式
  • Prototype 模式
  • Singleton 模式
  • Registry of Singleton 模式

出现的问题

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. 下面还有1种解决方法叫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

建造模式解决该问题
<span style="font-weight: normal;">public class Pizza { // 必须的 private final int size; // 可有可无的 private boolean cheese; 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; //由于size时必须的,所以设置为构造函数的参数 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; } }</span>

注意到现在Pizza是1个immutable class,所以它是线程安全的。又由于每个Builder's setter方法都返回1个Builder对象,所以可以串连起来调用。以下

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

由上面我们可以知道,建造模式,给了用户更大的自由,可以任选参数.

2014⑴1-09 18:21:17

Brave,Happy,Thanksgiving !


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐