Builder pattern code generation in IntelliJ

前端 未结 11 1235
猫巷女王i
猫巷女王i 2021-01-30 01:36

Is there any way to automate writing Builder patterns in IntelliJ?

For example, given this simple class:

class Film {
   private String title;
   private         


        
11条回答
  •  盖世英雄少女心
    2021-01-30 01:56

    I found the built-in builder pattern generation in IntelliJ to be a bit clunky for a few reasons:

    1. It needs to use an existing constructor as reference.
    2. It's not quickly accessible via the "Generate" menu (command+N on OS X).
    3. It only generates external Builder classes. As others have mentioned, it's very common to use static inner classes when implementing the builder pattern.

    The InnerBuilder plugin addresses all of these shortcomings, and requires no setup or configuration. Here's a sample Builder generated by the plugin:

    public class Person {
        private String firstName;
        private String lastName;
        private int age;
    
        private Person(Builder builder) {
            firstName = builder.firstName;
            lastName = builder.lastName;
            age = builder.age;
        }
    
        public static final class Builder {
            private String firstName;
            private String lastName;
            private int age;
    
            public Builder() {
            }
    
            public Builder firstName(String firstName) {
                this.firstName = firstName;
                return this;
            }
    
            public Builder lastName(String lastName) {
                this.lastName = lastName;
                return this;
            }
    
            public Builder age(int age) {
                this.age = age;
                return this;
            }
    
            public Person build() {
                return new Person(this);
            }
        }
    }
    

提交回复
热议问题