属于创建型模式 (共5种)

    目的:
    分离复杂对象的构建和表示;同样的构建过程可以创建不同的表示
    用于需要大量参数的对象的构建

    类图:
    image.png
    举例:
    步骤
    一个复杂的地形构建 :地形构建需要大量参数;
    地形类中聚合 相应的属性类
    image.png
    创建地形构建器接口 构建地形中各种属性 最后构建出完整地形 (分步构建最后合并)
    image.png
    具体的构建器 实现接口构建器 进行具体的构建
    image.png
    image.png

    个人构建器
    人有很多属性
    构建的时候有些属性用不到 可以分批构建
    在构建类中 新建静态内部类
    将属性 分批构建

    1. public class Person {
    2. int id;
    3. String name;
    4. int age;
    5. double weight;
    6. int score;
    7. Location loc;
    8. private Person() {}
    9. //内部类
    10. public static class PersonBuilder {
    11. Person p = new Person();
    12. public PersonBuilder basicInfo(int id, String name, int age) {
    13. p.id = id;
    14. p.name = name;
    15. p.age = age;
    16. return this;
    17. }
    18. public PersonBuilder weight(double weight) {
    19. p.weight = weight;
    20. return this;
    21. }
    22. public PersonBuilder score(int score) {
    23. p.score = score;
    24. return this;
    25. }
    26. public PersonBuilder loc(String street, String roomNo) {
    27. p.loc = new Location(street, roomNo);
    28. return this;
    29. }
    30. public Person build() {
    31. return p;
    32. }
    33. }
    34. }
    35. -----------------------------------------------------------
    36. class Location {
    37. String street;
    38. String roomNo;
    39. public Location(String street, String roomNo) {
    40. this.street = street;
    41. this.roomNo = roomNo;
    42. }
    43. }

    最后用法 构建时不需要的参数可不写
    image.png