Java 建造者Builder
import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; public class Builder<T> { private final Supplier<T> instantiator; private List<Consumer<T>> modifiers = new ArrayList<>(); public Builder(Supplier<T> instantiator) { this.instantiator = instantiator; } public static <T> Builder<T> of(Supplier<T> instantiator){ return new Builder<>(instantiator); } public <P1> Builder<T> with(Consumer1<T,P1> consumer1,P1 p1){ Consumer<T> c = instance -> consumer1.accept(instance,p1); modifiers.add(c); return this; } public interface Consumer1<T,P1> { void accept(T t,P1 p1); } public static void main(String[] args) { Builder.of(TestVo::new).with(TestVo::setId,"id值"); Builder.of(TestVo::new).with((t,p1) -> t.setId(p1),"id值"); } }
多余的就不说了,我相信代码Debug以下都能看懂
复制请注明出处,在世界中挣扎的灰太狼