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以下都能看懂

jdk8新特性

posted @ 2020-11-04 20:06  星小梦  阅读(289)  评论(0编辑  收藏  举报