别名:构建者模式,生成器模式


    之所有有这个模式,是因为传统的创建对象模式有很多的弊端,就拿一个最简单的例子,我们希望对象完成后,不能改变任何属性。如果使用传统的创建对象的方式

    • 如果直接使用构造器的模式,那么不同的要求就会创建很多的构造器,并且参数很多的情况下,使用构造器会造成很难理解。
    • 如果使用set,get的方式,那么在对象完成后内部的属性可能还会被修改

    使用建造者模式,可以很好的解决上面的问题。并且使用构建者模式创建对象的时候可以更方便的检验。
    ``

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