国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php框架 > 框架设计 > 设计模式:建造模式

设计模式:建造模式

来源:程序员人生   发布时间:2015-01-14 09:11:50 阅读次数:3707次

原文地址: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 !


生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生