How to implement the builder pattern in Java 8?

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

    You can check the lombok project

    For your case

    @Builder
    public class Person {
        private String name;
        private int age;
    }
    

    It would generate the code on the fly

    public class Person {
        private String name;
        private int age;
        public String getName(){...}
        public void setName(String name){...}
        public int getAge(){...}
        public void setAge(int age){...}
        public Person.Builder builder() {...}
    
        public static class Builder {
             public Builder withName(String name){...}
             public Builder withAge(int age){...}
             public Person build(){...}
        }        
    }
    

    Lombok do it on the compilation phase and is transparent for developers.

提交回复
热议问题