建造者模式(Builder Pattern)也叫做生成器模式,其定义如下:Separate the construction of a complex object from its representation so that the sameconstruction process can create different representations.(将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。) -设计模式之禅 第2版

    我认为这里的表示指的是对象的属性。整体的意思就是将属性的初始化逻辑交予建造者,然后实例化这个类时,调用构造者,然后对类的属性进行赋值,就像下面这样 建造者模式 - 图1```java package cn.zjm404.design.creat.builder;

    import lombok.ToString;

    @ToString public class A {

    1. private String v1;
    2. private String v2;
    3. public A (Builder builder){
    4. this.v1 = builder.v1;
    5. this.v2 = builder.v2;
    6. }
    7. public static class Builder{
    8. private String v1;
    9. private String v2;
    10. public A build(){
    11. //对属性进行一些判断,这里就不写了
    12. return new A(this);
    13. }
    14. public Builder setV1(String v1){
    15. this.v1 = v1;
    16. return this;
    17. }
    18. public Builder setV2(String v2){
    19. this.v2 = v2;
    20. return this;
    21. }
    22. }

    }

    class Run{ public static void main(String[] args){ A a = new A.Builder() .setV1(“hello”) .setV2(“world”) .build(); System.out.println(a); } }

    ``` 建造者和工厂模式比较像,但是不同的是,建造者是实例化同一个类,通过build的具体业务逻辑来生成不同的对象。而工厂模式是实例化不同的类。