卖热干面的启发 ---Builder 模式

5,318 阅读5分钟

看个故事

互联网寒冬来袭, 小光越来越觉得码农这个行当不太好混了. 年关将至, 思乡之情也是倍切. 心底一横, 要不直接回老家做点小买卖得了~

说做就做, 小光辞了工作, 回到老家武汉, 做起了卖热干面的行当.
小光秉着科学开店, 合理经营的心思, 走访老店, 探索人流, 最终把店开在了软件园旁边.

经过仔细他发现, 每个人点热干面时, 要的配料还各不相同, 有的要葱花, 有的不要葱花要香菜, 有的不要辣, 有的要加酸菜......
小光心想, 这可难不倒我, 你要什么不要什么一次性告诉我, 不就得了. 很快, 热干面程序出炉:

public class HotDryNoodles {

    private boolean addShallot;
    private boolean addParsley;
    private boolean addChili;
    private boolean addSauerkraut;

    public HotDryNoodles(boolean shallot, boolean parsley, boolean chili, boolean sauerkraut) {
        this.addShallot = shallot;
        this.addParsley = parsley;
        this.addChili = chili;
        this.addSauerkraut = sauerkraut;
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder("A bowl of hot-dry noodles has:");

        if (this.addShallot) {
            builder.append("葱花.");
        }

        if (this.addParsley) {
            builder.append("香菜.");
        }

        if (this.addChili) {
            builder.append("辣椒.");
        }

        if (this.addSauerkraut) {
            builder.append("酸菜.");
        }

        return builder.toString();
    }
}

注意: 构造函数的参数是有顺序的(葱花.香菜.辣椒.酸菜).

你还别说, 大武汉的码农们还真挺爱吃热干面, 一会生意就上门了:

A: 老板, 热干面一份, 加葱, 加香菜, 放点酸菜.
B: 老板, 热干面, 加葱, 放点酸菜.

小光, 一声"好嘞", 立马开工:

public class XiaoGuang {

    public static void main(String[] args) {

        // A
        HotDryNoodles noodlesA = new HotDryNoodles(true, true, false, true);
        System.out.println("Customer A wants: " + noodlesA);

        // B
        HotDryNoodles noodlesB = new HotDryNoodles(true, false, false, true);
        System.out.println("Customer B wants: " + noodlesB);
    }
}

很快出炉:

Customer A wants: A bowl of hot-dry noodles has:葱花.香菜.酸菜.
Customer B wants: A bowl of hot-dry noodles has:葱花.酸菜.

完美~

这时, 来了一哥们儿: 老板, 一碗热干面, 加辣椒, 不放葱.
小光吭哧吭哧忙活上了, 结果一端出来, 人哥们儿不乐意了, 怎么就放葱了啊, 还没有放辣椒~~
原来是小光搞错了顺序(参数顺序)~ (也怪这哥们不按套路出牌啊)

没有办法, 重做一份咯~ (为了用户体验)

收摊之后, 小光是痛定思痛啊, 现在的工序的确很容易出问题啊:

  • 目前的(参数)顺序是固定的, 客户要求各异, 根本不按套路来, 就很容易出错.
  • 目前的(参数)个数是固定的, 大多数客户都选择默认, 只额外提一两个要求.

小光思考着怎么改进, 突然灵光一现:

这个不就是构建对象时有大量可选参数的问题吗?
我可以使用Builder模式来解决这个问题啊. 原来编程无处不在, 小光暗思.

然后就开始动手改造工序了:

  • 他买了张桌子, 用来作为配料台(Builder)
  • 把配料(葱花.香菜.辣椒.酸菜)从他的热干面(HotDryNoodlesWithBuilder)构造中移到配料台放着了.
  • 让客户自己选择添加什么配料, 自己从配料台上选择添加.

那么, 添加配料的过程编程自取了:

如此一来, 他不仅仅释放了自己的劳动力, 也不用费力去记客户到底要哪些不要哪些的, 把基本的面做好, 放在调料台, 让用户自己添加吧~~

改造后的热干面工序:

public class HotDryNoodlesWithBuilder {

    private boolean addShallot;
    private boolean addParsley;
    private boolean addChili;
    private boolean addSauerkraut;

    public HotDryNoodlesWithBuilder(Builder builder) {
        this.addShallot = builder.addShallot;
        this.addParsley = builder.addParsley;
        this.addChili = builder.addChili;
        this.addSauerkraut = builder.addSauerkraut;
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder("A bowl of hot-dry noodles has:");

        if (this.addShallot) {
            builder.append("葱花.");
        }

        if (this.addParsley) {
            builder.append("香菜.");
        }

        if (this.addChili) {
            builder.append("辣椒.");
        }

        if (this.addSauerkraut) {
            builder.append("酸菜.");
        }

        return builder.toString();
    }


    public static class Builder {

        private boolean addShallot;
        private boolean addParsley;
        private boolean addChili;
        private boolean addSauerkraut;

        public Builder() {

        }

        public Builder withShallot() {
            this.addShallot = true;
            return this;
        }

        public Builder withParsley() {
            this.addParsley = true;
            return this;
        }

        public Builder withChili() {
            this.addChili = true;
            return this;
        }

        public Builder withSauerkraut() {
            this.addSauerkraut = true;
            return this;
        }

        public HotDryNoodlesWithBuilder build() {
            return new HotDryNoodlesWithBuilder(this);
        }
    }

}

来看看用户怎么用的:

public class XiaoGuang {

    public static void main(String[] args) {

        // with builder
        HotDryNoodlesWithBuilder noodlesC = new HotDryNoodlesWithBuilder.Builder()
                .withChili()
                .withParsley()
                .build();
        System.out.println("Customer C wants: " + noodlesC);

        HotDryNoodlesWithBuilder noodlesD = new HotDryNoodlesWithBuilder.Builder()
                .withChili()
                .withParsley()
                .withSauerkraut()
                .withShallot()
                .build();
        System.out.println("Customer D wants: " + noodlesD);
    }
}

结果不能太满意:

Customer C wants: A bowl of hot-dry noodles has:香菜.辣椒.
Customer D wants: A bowl of hot-dry noodles has:葱花.香菜.辣椒.酸菜.

再也没有用户抱怨说小光搞错了, 想要什么自己加, 顺序也无所谓了. 小光也有更多的时间服务更多的客户了...
看着来来往往的吃客, 小光憧憬着: 眼看就可以开分店, 连锁店, 上市, 当董事长, 迎娶白富美, 走上人生巅峰了, 哈哈哈哈哈.

故事之后

让我们重温下GoF设计模式中的Builder模式:

builde

Buidler模式, 是一种创建型的设计模式.
通常用来将一个复杂的对象的构造过程分离, 让使用者可以根据需要选择创建过程.
另外, 当这个复杂的对象的构造包含很多可选参数时, 那Builder模式可以说是不二之选了.

从这个故事中, 我们可以看到, 当热干面的配料参数太多时, 我们很难去控制, 一旦弄错了参数顺序, 客户就无法接受~

再来看下本故事中改造后的工序对应Builder模式的关系:

builder-2

一般来说, Builder常常作为实际产品的静态内部类来实现(提高内聚性).
故而Product,Director, Builder常常是在一个类文件中, 例如本例中的HotDryNoodlesWithBuilder.java.
这里为了更好的对应Builder模式的类图关系, 将HotDryNoodlesWithBuilder画了两个~.

扩展阅读

作为Java/Android开发者, 如果你想设计一个通用的库, Builder模式几乎肯定是会用到的, 我们需要提供良好的入口/接口来使用者可以弹性地构造他们需要的对象.

像一些优秀的开源库, 例如Glide, OkHttp等都在构造Glide, OkHttpClient时用到Builder模式, 例如OkHttpClient的创建, 如下节选OkHttpClient.java的代码:

public class OkHttpClient implements Cloneable, Call.Factory {
  public OkHttpClient() {
    this(new Builder());
  }

  private OkHttpClient(Builder builder) {
    this.dispatcher = builder.dispatcher;
    this.proxy = builder.proxy;
    this.protocols = builder.protocols;
    this.connectionSpecs = builder.connectionSpecs;
    this.interceptors = Util.immutableList(builder.interceptors);
    this.networkInterceptors = Util.immutableList(builder.networkInterceptors);
    this.proxySelector = builder.proxySelector;
    this.cookieJar = builder.cookieJar;
    this.cache = builder.cache;
    this.internalCache = builder.internalCache;
    this.socketFactory = builder.socketFactory;

    // more code...
  }

  public static final class Builder {

    public Builder() {
      ...
    }


    public Builder cache(Cache cache) {
      ...
    }

    public Builder dispatcher(Dispatcher dispatcher) {
      ...
    }

    public Builder protocols(List protocols) {
       ...
    }

    public List networkInterceptors() {
      ...
    }

    public Builder addNetworkInterceptor(Interceptor interceptor) {
      ...
    }

    public OkHttpClient build() {
      return new OkHttpClient(this);
    }
  }
}

是不是和小光设计的HotDryNoodlesWithBuilder很像...

生活还将继续, 小光继续奋斗着, 憧憬自己的人生巅峰梦~