1 重点掌握
1.1 3.1案例
1.2 实现构建模式的另一种形式
参考ddd领域设计
https://www.cnblogs.com/1446358788-qq/articles/15319451.html
创建对象的时候用factory工厂类创建(一定把必输项都带上),每次变更字段的时候,在Entity中写方法changeColum方法,每次先根据主键查Entity,然后在根据查出来的Entity变更某些字段。
1.3 与Lombok的builder的区别
虽然Lombok提供了Builder注解,但是本节主要是解决必输项与非必输的灵活模式,LomBok的builder注解不会有必输非必输方面的控制。
2 课程内容
2.1 多个构造器使用有参构造和JavaBeans的弊端
构造器有多个,维护成本和阅读成本变大
JavaBeans,可能导致状态不一致(必输项未输)和线程安全问题(第15条)
3 实战演练
3.1 多个构建器实例
构建器demo
package com.ddwei.test.core.chapter3.demo31; public class Person { private Boolean breathFlg; //必输项 private String hairColor; //可选项 private String tshirt; //可选项 @Override public String toString() { return "Builder{" + "breathFlg=" + breathFlg + ", hairColor='" + hairColor + '\'' + ", tshirt='" + tshirt + '\'' + '}'; } public static class Builder{ private Boolean breathFlg; private String hairColor; private String tshirt; public Builder(boolean breathFlg){ this.breathFlg = breathFlg; } public Builder hairColer(String hairColor){ this.hairColor = hairColor; return this; } public Builder tshirt(String tshirt){ this.tshirt = tshirt; return this; } public Person build(){ return new Person(this); } } private Person(Builder builder){ breathFlg = builder.breathFlg; hairColor = builder.hairColor; tshirt = builder.tshirt; } }
构建器test
package com.ddwei.test.core.chapter3.demo31; /** * @author weidoudou * @date 2022/4/18 8:10 **/ public class PersonTest { public static void main(String[] args) { //是否呼吸为必输, 其余非必输属性 Person person = new Person.Builder(true).hairColer("blue").tshirt("Yes").build(); System.out.println(person.toString()); } }
打印日志:
Builder{breathFlg=true, hairColor='blue', tshirt='Yes'} Process finished with exit code 0
诸葛