设计模式之建造者模(Builder)

2019-04-13 16:56发布

设计模式之建造者模(Builder)

本系列为 https://github.com/iluwatar/java-design-patterns 阅读笔记
之前读《java effective》时了解到Builder模式
至于为什么出现Builder模式参见 https://blog.csdn.net/lms1719/article/details/70741691
这个模式看似简单还是需要写一遍才行,
我敲了一遍中间出了很多错
Builder 声明public static class Builder public class Hero { private final String name; private final String gen; private final LocalDate birthday; public Hero(Builder builder) {// this.name = builder.name; this.gen = builder.gen; this.birthday = builder.birthday; } public static class Builder { private final String name; private String gen; private LocalDate birthday; public Builder(String name) {//必填参数 this.name = name; } public Builder setGen(String gen){ this.gen = gen; return this;//返回自身,链式创建 } public Builder setBirthDay(LocalDate day){ this.birthday = day; return this; } public Hero build(){//构造完成之后调用外部类构造函数 return new Hero(this); } } public static void main(String[] args) { Hero build = new Builder("tom").setBirthDay(LocalDate.now()).build(); System.out.println(build); } }