原创

java中的建造者设计模式

1、怎么使用

@Builder
public class BuilderTest {
    private String name;
    private String age;

    public static void main(String[] args) {
        BuilderTest.builder().name("xxxx").age("11").build();
    }
}
一个@Builder注解搞定

2、对应的class

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package net.gzcx;

public class BuilderTest {
    private String name;
    private String age;

    public static void main(String[] args) {
        builder().name("xxxx").age("11").build();
    }

    BuilderTest(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public static BuilderTestBuilder builder() {
        return new BuilderTestBuilder();
    }

    public static class BuilderTestBuilder {
        private String name;
        private String age;

        BuilderTestBuilder() {
        }

        public BuilderTestBuilder name(String name) {
            this.name = name;
            return this;
        }

        public BuilderTestBuilder age(String age) {
            this.age = age;
            return this;
        }

        public BuilderTest build() {
            return new BuilderTest(this.name, this.age);
        }

        public String toString() {
            return "BuilderTest.BuilderTestBuilder(name=" + this.name + ", age=" + this.age + ")";
        }
    }
}

3、说明

  • 在类中,创建一个静态内部类,包含外部类的全部属性;
  • 在内部类中,为每一个属性进行赋值;
  • 内部类中创建 build 方法,返回外部类对象
  • 在外部类中创建静态 builder方法,返回内部类对象
正文到此结束
本文目录