How to implement the builder pattern in Java 8?

前端 未结 6 2081
忘了有多久
忘了有多久 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:25

    public class PersonBuilder {
        public String salutation;
        public String firstName;
        public String middleName;
        public String lastName;
        public String suffix;
        public Address address;
        public boolean isFemale;
        public boolean isEmployed;
        public boolean isHomewOwner;
    
        public PersonBuilder with(
            Consumer builderFunction) {
            builderFunction.accept(this);
            return this;
        }
    
    
        public Person createPerson() {
            return new Person(salutation, firstName, middleName,
                    lastName, suffix, address, isFemale,
                    isEmployed, isHomewOwner);
        }
    }
    

    Usage

    Person person = new PersonBuilder()
        .with($ -> {
            $.salutation = "Mr.";
            $.firstName = "John";
            $.lastName = "Doe";
            $.isFemale = false;
        })
        .with($ -> $.isHomewOwner = true)
        .with($ -> {
            $.address =
                new PersonBuilder.AddressBuilder()
                    .with($_address -> {
                        $_address.city = "Pune";
                        $_address.state = "MH";
                        $_address.pin = "411001";
                    }).createAddress();
        })
        .createPerson();
    

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

    Disclaimer: I am the author of the post

提交回复
热议问题