Lambda实现通用的建造者工具

Builder 建造者

public class Builder<T> {

    /**
     * 存储调用方 指定构造类的 构造器
     */
    private final Supplier<T> constructor;

    /**
     * 存储 指定类 所有需要初始化的类属性
     */
    private final List<Consumer<T>> dInjects = new ArrayList<>();

    /**
     * 构造方法
     *
     * @param constructor 供给型参数
     */
    public Builder(Supplier<T> constructor) {
        this.constructor = constructor;
    }

    /**
     * builder方法
     *
     * @param constructor
     * @param <T>
     * @return
     */
    public static <T> Builder<T> builder(Supplier<T> constructor) {
        return new Builder<>(constructor);
    }

    public <P> Builder<T> with(Builder.InjectConsumer<T, P> consumer, P p) {
        Consumer<T> c = instance -> consumer.accept(instance, p);
        dInjects.add(c);
        return this;
    }

    public T build() {
        // 调用supplier 生成类实例
        T instance = constructor.get();
        // 调用传入的setter方法,完成属性初始化
        dInjects.forEach(dInject -> dInject.accept(instance));
        // 返回 建造完成的类实例
        return instance;
    }

    @FunctionalInterface
    public interface InjectConsumer<T, P> {
        void accept(T t, P p);
    }
}

实体类对象

public class Student {

    private Long id;
    public String name;
    public Integer sex;
    public Integer grade;
    public String address;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public Integer getGrade() {
        return grade;
    }
    public void setGrade(Integer grade) {
        this.grade = grade;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                ", grade=" + grade +
                ", address='" + address + '\'' +
                '}';
    }
}

构建方式展示

        Student student = Builder.builder(Student::new)
                .with(Student::setName, "唐川疆")
                .with(Student::setSex, 1)
                .with(Student::setGrade, 7)
                .with(Student::setAddress, "流碑池")
                .build();
        System.out.println("student = " + student);

展示打印结果

student = Student{id=null, name=‘唐川疆’, sex=1, grade=7, address=‘流碑池’}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值