How to implement the builder pattern in Java 8?

前端 未结 6 2078
忘了有多久
忘了有多久 2020-12-04 08:58

Implement the builder pattern prior to Java 8 has lots of tedious, nearly duplicated code; the builder itself is typically boilerplate code. Some duplicate code detectors co

6条回答
  •  温柔的废话
    2020-12-04 09:13

    We can use Consumer functional interface of Java 8 to avoid multiple getter/setter methods.

    Refer the below-updated code with Consumer interface.

    import java.util.function.Consumer;
    
    public class Person {
    
        private String name;
    
        private int age;
    
        public Person(Builder Builder) {
            this.name = Builder.name;
            this.age = Builder.age;
        }
    
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Person{");
            sb.append("name='").append(name).append('\'');
            sb.append(", age=").append(age);
            sb.append('}');
            return sb.toString();
        }
    
        public static class Builder {
    
            public String name;
            public int age;
    
            public Builder with(Consumer function) {
                function.accept(this);
                return this;
            }
    
            public Person build() {
                return new Person(this);
            }
        }
    
        public static void main(String[] args) {
            Person user = new Person.Builder().with(userData -> {
                userData.name = "test";
                userData.age = 77;
            }).build();
            System.out.println(user);
        }
    }
    

    Refer the below link to know the detailed information with the different examples.

    https://medium.com/beingprofessional/think-functional-advanced-builder-pattern-using-lambda-284714b85ed5

    https://dkbalachandar.wordpress.com/2017/08/31/java-8-builder-pattern-with-consumer-interface/

提交回复
热议问题