baby sword‘s blog baby sword‘s blog
首页
  • java基础
  • java进阶
大数据
  • mysql

    • mysql索引
    • mysql日志
  • redis

    • 单机下的redis
    • 集群下的redis
  • Spring
  • springboot
  • RPC
  • netty
  • mybatis
  • maven
  • 消息队列
  • kafka
  • zookeeper
  • rocketmq
  • 七大设计原则
  • 创建型模式
  • 结构型模式
  • 行为型模式
  • SpringCloud

    • eureka
  • SpringCloud Alibaba

    • nacos
  • 计算机网络
  • 操作系统
  • 算法
  • 个人项目
  • 个人面试面经
  • 八股记忆
  • 工作积累
  • 逻辑题
  • 面试

    • 百度后端实习二面
GitHub (opens new window)

zhengjian

不敢承担失去的风险,是不可能抓住梦想的
首页
  • java基础
  • java进阶
大数据
  • mysql

    • mysql索引
    • mysql日志
  • redis

    • 单机下的redis
    • 集群下的redis
  • Spring
  • springboot
  • RPC
  • netty
  • mybatis
  • maven
  • 消息队列
  • kafka
  • zookeeper
  • rocketmq
  • 七大设计原则
  • 创建型模式
  • 结构型模式
  • 行为型模式
  • SpringCloud

    • eureka
  • SpringCloud Alibaba

    • nacos
  • 计算机网络
  • 操作系统
  • 算法
  • 个人项目
  • 个人面试面经
  • 八股记忆
  • 工作积累
  • 逻辑题
  • 面试

    • 百度后端实习二面
GitHub (opens new window)
  • 设计模式七大原则
  • 创建型模式

    • 简单工厂模式
    • 工厂方法模式
    • 抽象工厂模式
    • 单例模式
    • 建造者模式
      • 原型模式
    • 结构型模式

    • 行为型模式

    • UML

    • 设计模式
    • 创建型模式
    xugaoyi
    2023-08-14
    目录

    建造者模式

    # 为什么需要建造者模式

    一般我们创建对象,通过new关键字创建对象,且通过set方法来给对象赋值的。

    如下,我们创建一个配置类ResourcePoolConfig

    1

    一般我们会按照如下的方式去创建对象

    public class ResourcePoolConfig {
    
        private static final int DEFAULT_MAX_TOTAL = 8;
    
        private static final int DEFAULT_MAX_IDLE = 8;
    
        private static final int DEFAULT_MIN_IDLE = 0;
    
    
        private String name;
    
        private int maxTotal = DEFAULT_MAX_TOTAL;
    
        private int maxIdle = DEFAULT_MAX_IDLE;
    
        private int minIdle = DEFAULT_MIN_IDLE;
    
    
        public ResourcePoolConfig(String name, Integer maxTotal, Integer maxIdle, Integer minIdle) {
            if (name == null || "".equals(name)) {
                throw new IllegalArgumentException("name should not be empty.");
            }
            this.name = name;
    
            if (maxTotal != null) {
                if (maxTotal <= 0) {
                    throw new IllegalArgumentException("maxTotal should be positive.");
                }
                this.maxTotal = maxTotal;
            }
    
            if (maxIdle != null) {
                if (maxIdle < 0) {
                    throw new IllegalArgumentException("maxIdle should not be negative.");
                }
                this.maxIdle = maxIdle;
            }
    
            if (minIdle != null) {
                if (minIdle < 0) {
                    throw new IllegalArgumentException("minIdle should not be negative.");
                }
                this.minIdle = minIdle;
            }
    
        }
    //...省略getter方法...
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    1. 对于必填属性,我们在构造方法中必须定义好
    2. 对于非必填属性,我们对属性设置默认值,并且当构造方法中对应的属性不为null时,我们在构造方法中使用set语句对属性进行赋值。

    劣势:

    当我们的成员变量足够多时,我们的构造方法就会非常冗长,代码在可读性和易用性上都会变差。在使用构造函数的时候,我们就容易搞错各参数的顺序,传递进错误的参数值,导致非常隐蔽的 bug。

    如何解决?

    1. 构造方法的成员变量中只放必填参数,其他的非必填参数在构造完后通过set方法改变
    public class ResourcePoolConfig {
        private static final int DEFAULT_MAX_TOTAL = 8;
        private static final int DEFAULT_MAX_IDLE = 8;
        private static final int DEFAULT_MIN_IDLE = 0;
    
        private String name;
        private int maxTotal = DEFAULT_MAX_TOTAL;
        private int maxIdle = DEFAULT_MAX_IDLE;
        private int minIdle = DEFAULT_MIN_IDLE;
    
        public ResourcePoolConfig(String name) {
            if (StringUtils.isBlank(name)) {
                throw new IllegalArgumentException("name should not be empty.");
            }
            this.name = name;
        }
    
        public void setMaxTotal(int maxTotal) {
            if (maxTotal <= 0) {
                throw new IllegalArgumentException("maxTotal should be positive.");
            }
            this.maxTotal = maxTotal;
        }
    
        public void setMaxIdle(int maxIdle) {
            if (maxIdle < 0) {
                throw new IllegalArgumentException("maxIdle should not be negative.");
            }
            this.maxIdle = maxIdle;
        }
    
        public void setMinIdle(int minIdle) {
            if (minIdle < 0) {
                throw new IllegalArgumentException("minIdle should not be negative.");
            }
            this.minIdle = minIdle;
        }
        //...省略getter方法...
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    // ResourcePoolConfig使用举例
    ResourcePoolConfig config = new ResourcePoolConfig("dbconnectionpool");
    config.setMaxTotal(16);
    config.setMaxIdle(8);
    
    1
    2
    3
    4

    当然,以上的形式虽然减少了参数列表的数量,但是还会出现以下的问题

    • 我们刚刚讲到,name 是必填的,所以,我们把它放到构造函数中,强制创建对象的时候就设置。如果必填的配置项有很多,把这些必填配置项都放到构造函数中设置,那构造函数就又会出现参数列表很长的问题。如果我们把必填项也通过 set() 方法设置,那校验这些必填项是否已经填写的逻辑就无处安放了。

    • 除此之外,假设配置项之间有一定的依赖关系,比如,如果用户设置了 maxTotal、maxIdle、minIdle 其中一个,就必须显式地设置另外两个;或者配置项之间有一定的约束条件,比如,maxIdle 和 minIdle 要小于等于 maxTotal。如果我们继续使用现在的设计思路,那这些配置项之间的依赖关系或者约束条件的校验逻辑就无处安放了。【总不可能放在set中吧】

    • 如果我们希望 ResourcePoolConfig 类对象是不可变对象,也就是说,对象在创建好之后,就不能再修改内部的属性值。要实现这个功能,我们就不能在ResourcePoolConfig 类中暴露 set() 方法

    # 如何使用建造者模式

    我们可以把校验逻辑放置到 Builder 类中,先创建建造者,并且通过 set() 方法设置建造者的变量值,然后在使用 build() 方法真正创建对象之前,做集中的校验,校验通过之后才会创建对象。除此之外,我们把ResourcePoolConfig 的构造函数改为 private 私有权限。这样我们就只能通过建造者来创建 ResourcePoolConfig 类对象。并且,ResourcePoolConfig 没有提供任何 set() 方法,这样我们创建出来的对象就是不可变对象了

    public class ResourcePoolConfig {
        private String name;
        private int maxTotal;
        private int maxIdle;
        private int minIdle;
    
    
        private ResourcePoolConfig(Builder builder) {
            this.name = builder.name;
            this.maxTotal = builder.maxTotal;
            this.maxIdle = builder.maxIdle;
            this.minIdle = builder.minIdle;
        }
    //...省略getter方法...
        //我们将Builder类设计成了ResourcePoolConfig的内部类。
    
        //我们也可以将Builder类设计成独立的非内部类ResourcePoolConfigBuilder。
        public static class Builder {
            private static final int DEFAULT_MAX_TOTAL = 8;
            private static final int DEFAULT_MAX_IDLE = 8;
            private static final int DEFAULT_MIN_IDLE = 0;
    
            private String name;
            private int maxTotal = DEFAULT_MAX_TOTAL;
            private int maxIdle = DEFAULT_MAX_IDLE;
            private int minIdle = DEFAULT_MIN_IDLE;
    
    
            public ResourcePoolConfig build() {
    // 校验逻辑放到这里来做,包括必填项校验、依赖关系校验、约束条件校验等
                if (StringUtils.isBlank(name)) {
                    throw new IllegalArgumentException("...");
                }
                if (maxIdle > maxTotal) {
                    throw new IllegalArgumentException("...");
                }
                if (minIdle > maxTotal || minIdle > maxIdle) {
                    throw new IllegalArgumentException("...");
                }
                return new ResourcePoolConfig(this);
            }
    
    
            public Builder setName(String name) {
                if (StringUtils.isBlank(name)) {
                    throw new IllegalArgumentException("...");
                }
                this.name = name;
                return this;
            }
    
    
            public Builder setMaxTotal(int maxTotal) {
    
                if (maxTotal <= 0) {
                    throw new IllegalArgumentException("...");
                }
                this.maxTotal = maxTotal;
                return this;
            }
    
    
            public Builder setMaxIdle(int maxIdle) {
                if (maxIdle < 0) {
                    throw new IllegalArgumentException("...");
                }
                this.maxIdle = maxIdle;
                return this;
            }
    
    
            public Builder setMinIdle(int minIdle) {
                if (minIdle < 0) {
                    throw new IllegalArgumentException("...");
                }
                this.minIdle = minIdle;
                return this;
            }
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
        ResourcePoolConfig config = new ResourcePoolConfig.Builder()
                .setName("dbconnectionpool")
                .setMaxTotal(16)
                .setMaxIdle(10)
                .setMinIdle(12)
                .build();
    
    1
    2
    3
    4
    5
    6

    如果构造函数参数过多,我们就需要考虑使用建造者模式,先设置建造者的变量,然后再一次性地创建对象,让对象一直处于有效状态。

    # 与工厂模式有什么区别

    工厂模式是用来创建不同但是相关类型的对象(继承同一父类或者接口的一组子

    类),由给定的参数来决定创建哪种类型的对象。建造者模式是用来创建一种类型的复杂对

    象,通过设置不同的可选参数,“定制化”地创建不同的对象。

    顾客走进一家餐馆点餐,我们利用工厂模式,根据用户不同的选择,来制作不同的食物,比

    如披萨、汉堡、沙拉。对于披萨来说,用户又有各种配料可以定制,比如奶酪、西红柿、起

    司,我们通过建造者模式根据用户选择的不同配料来制作披萨

    编辑 (opens new window)
    上次更新: 2024/02/22, 14:03:19
    单例模式
    原型模式

    ← 单例模式 原型模式→

    最近更新
    01
    spark基础
    02-22
    02
    mysql读写分离和分库分表
    02-22
    03
    数据库迁移
    02-22
    更多文章>
    Theme by Vdoing | Copyright © 2019-2024 Evan Xu | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式