建造者模式:Builder Pattern,将一个复杂对象的构建过程与它的表示分离,使得同样的构建过程可以创建不同的表示,属于创建型设计模式

    建造者模式和工厂模式区别:

    • 建造者模式:一般用于创建复杂对象
    • 工厂模式:一般用于创建简单对象

    简单实现:

    1. public class BuilderDemo {
    2. public static void main(String[] args) {
    3. // 测试
    4. Product product = Product.builder()
    5. .setName("李四").setPrice(18).setSize(20)
    6. .build();
    7. System.out.println(product);
    8. }
    9. @Data
    10. static class Product {
    11. private String name;
    12. private Integer price;
    13. private Integer size;
    14. public static Builder builder() {
    15. // 返回一个构建器
    16. return new Builder();
    17. }
    18. private Product(String name, Integer price, Integer size) {
    19. this.name = name;
    20. this.price = price;
    21. this.size = size;
    22. }
    23. static class Builder {
    24. private String name;
    25. private Integer price;
    26. private Integer size;
    27. public Builder setName(String name) {
    28. this.name = name;
    29. return this;
    30. }
    31. public Builder setPrice(Integer price) {
    32. this.price = price;
    33. return this;
    34. }
    35. public Builder setSize(Integer size) {
    36. this.size = size;
    37. return this;
    38. }
    39. // 在调用builder时才会创建实例
    40. public Product build() {
    41. return new Product(name, price, size);
    42. }
    43. }
    44. }
    45. }