设计模式之建造者模式

建造者模式

文章目录

  • 建造者模式
    • 1.定义
    • 2.示例代码

1.定义

建造者模式(Builder Pattern)也叫做生成器模式,其定义如下:

Separate the construction of a complex object from its representation so that the same construction process can create different representations.(将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。)

2.示例代码

直接使用lombok@Builder注解解释下

我们这边可以使用lombok的@Builder注解类反编译class文件看下结构就知道了

@Data
@Builder
public class Teacher implements Serializable {
    private static final long serialVersionUID = 4099723881512840653L;
    private String id;
    private String name;
    private Integer age;
}

反编译后的class,由此可以看出字段很多时使用建造者模式。

public class Teacher implements Serializable {
    private static final long serialVersionUID = 4099723881512840653L;
    private String id;
    private String name;
    private Integer age;

    public static TeacherBuilder builder() {
        return new TeacherBuilder();
    }
	.....

    public static class TeacherBuilder {
        private String id;
        private String name;
        private Integer age;

        TeacherBuilder() {
        }

        public TeacherBuilder id(final String id) {
            this.id = id;
            return this;
        }

        public TeacherBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public TeacherBuilder age(final Integer age) {
            this.age = age;
            return this;
        }

        public Teacher build() {
            return new Teacher(this.id, this.name, this.age);
        }
		...
    }

3.开源组件中使用

举几个例子

  1. okhttp
  2. flowable
  3. fegin

明细代码就不一一展示,读者可以自己去验证。

你可能感兴趣的:(设计模式,建造者模式)