首页 > 代码库 > 设计模式:建造模式

设计模式:建造模式

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

Creational 模式

物件的产生需要消耗系统资源,所以如何有效率的产生、管理 与操作物件,一直都是值得讨论的课题, Creational 模式即与物件的建立相关,在这个分类下的模式给出了一些指导原则及设计的方向。下面列举到的全属于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. 下面还有一种解决方法叫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是一个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 !


设计模式:建造模式