com.github.javaclub.toolbox.model.BeanBuilder Maven / Gradle / Ivy
/*
* @(#)BeanBuilder.java 2024-04-23 09:31:25
*
* Copyright (c) 2024 - 2099. All Rights Reserved.
*
*/
package com.github.javaclub.toolbox.model;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* BeanBuilder
*
* @author Gerald Chen
* @version $Id: BeanBuilder.java 2024-04-23 09:31:25 Exp $
*/
public class BeanBuilder {
private final Supplier instantiator;
private List> modifiers = new ArrayList<>();
public BeanBuilder(Supplier instantiator) {
this.instantiator = instantiator;
}
public static BeanBuilder of(Supplier instantiator) {
return new BeanBuilder<>(instantiator);
}
public BeanBuilder with(Consumer1 consumer, P1 p1) {
Consumer c = instance -> consumer.accept(instance, p1);
modifiers.add(c);
return this;
}
public BeanBuilder with(Consumer2 consumer, P1 p1, P2 p2) {
Consumer c = instance -> consumer.accept(instance, p1, p2);
modifiers.add(c);
return this;
}
public BeanBuilder with(Consumer3 consumer, P1 p1, P2 p2, P3 p3) {
Consumer c = instance -> consumer.accept(instance, p1, p2, p3);
modifiers.add(c);
return this;
}
public T build() {
T value = instantiator.get();
modifiers.forEach(modifier -> modifier.accept(value));
modifiers.clear();
return value;
}
/**
* 1 参数 Consumer
*/
@FunctionalInterface
public interface Consumer1 {
void accept(T t, P1 p1);
}
/**
* 2 参数 Consumer
*/
@FunctionalInterface
public interface Consumer2 {
void accept(T t, P1 p1, P2 p2);
}
/**
* 3 参数 Consumer
*/
@FunctionalInterface
public interface Consumer3 {
void accept(T t, P1 p1, P2 p2, P3 p3);
}
}