建造者模式(Builder Pattern)也叫做生成器模式,其定义如下:Separate the construction of a complex object from its representation so that the sameconstruction process can create different representations.(将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。) -设计模式之禅 第2版
我认为这里的表示指的是对象的属性。整体的意思就是将属性的初始化逻辑交予建造者,然后实例化这个类时,调用构造者,然后对类的属性进行赋值,就像下面这样
```java
package cn.zjm404.design.creat.builder;
import lombok.ToString;
@ToString public class A {
private String v1;private String v2;public A (Builder builder){this.v1 = builder.v1;this.v2 = builder.v2;}public static class Builder{private String v1;private String v2;public A build(){//对属性进行一些判断,这里就不写了return new A(this);}public Builder setV1(String v1){this.v1 = v1;return this;}public Builder setV2(String v2){this.v2 = v2;return this;}}
}
class Run{ public static void main(String[] args){ A a = new A.Builder() .setV1(“hello”) .setV2(“world”) .build(); System.out.println(a); } }
``` 建造者和工厂模式比较像,但是不同的是,建造者是实例化同一个类,通过build的具体业务逻辑来生成不同的对象。而工厂模式是实例化不同的类。
