gball个人知识库
首页
基础组件
基础知识
算法&设计模式
  • 操作手册
  • 数据库
  • 极客时间
  • 每日随笔
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
  • 画图工具 (opens new window)
关于
  • 网盘 (opens new window)
  • 分类
  • 标签
  • 归档
项目
GitHub (opens new window)

ggball

后端界的小学生
首页
基础组件
基础知识
算法&设计模式
  • 操作手册
  • 数据库
  • 极客时间
  • 每日随笔
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
  • 画图工具 (opens new window)
关于
  • 网盘 (opens new window)
  • 分类
  • 标签
  • 归档
项目
GitHub (opens new window)
  • 面试

  • 数据库

  • linux

  • node

  • tensorFlow

  • 基础组件

  • 基础知识

  • 算法与设计模式

  • 分布式

  • 疑难杂症

  • go学习之旅

  • 极客时间

    • 设计模式之美

      • 开篇词 (1讲)

      • 设计模式学习导读 (3讲)

      • 设计原则与思想:面向对象 (11讲)

      • 设计原则与思想:设计原则 (12讲)

      • 设计原则与思想:规范与重构 (11讲)

      • 设计原则与思想:总结课 (3讲)

      • 设计模式与范式:创建型 (7讲)

        • 单例模式(上):为什么说支持懒加载的双重检测不比饿汉式更优?
        • 单例模式(中):我为什么不推荐使用单例模式?又有何替代方案?
        • 单例模式(下):如何设计实现一个集群环境下的分布式单例模式?
        • 工厂模式(上):我为什么说没事不要随便用工厂模式创建对象?
        • 工厂模式(下):如何设计实现一个DependencyInjection框架?
        • 建造者模式:详解构造函数、set方法、建造者模式三种对象创建方式
          • 为什么需要建造者模式?
          • 与工厂模式有何区别?
          • 重点回顾
          • 课堂讨论
          • 精选评论
        • 原型模式:如何最快速地clone一个HashMap散列表?
      • 设计模式与范式:结构型 (8讲)

      • 设计模式与范式:行为型 (18讲)

      • 设计模式与范式:总结课 (2讲)

      • 开源与项目实战:开源实战 (14讲)

      • 开源与项目实战:项目实战 (9讲)

      • 开源与项目实战:总结课 (2讲)

      • 不定期加餐 (11讲)

      • 结束语 (1讲)

    • Redis核心技术与实战

建造者模式:详解构造函数、set方法、建造者模式三种对象创建方式

# 46 | 建造者模式:详解构造函数、set方法、建造者模式三种对象创建方式

上两节课中,我们学习了工厂模式,讲了工厂模式的应用场景,并带你实现了一个简单的DI容器。今天,我们再来学习另外一个比较常用的创建型设计模式,Builder模式,中文翻译为建造者模式或者构建者模式,也有人叫它生成器模式。

实际上,建造者模式的原理和代码实现非常简单,掌握起来并不难,难点在于应用场景。比如,你有没有考虑过这样几个问题:直接使用构造函数或者配合set方法就能创建对象,为什么还需要建造者模式来创建呢?建造者模式和工厂模式都可以创建对象,那它们两个的区别在哪里呢?

话不多说,带着上面两个问题,让我们开始今天的学习吧!

# 为什么需要建造者模式?

在平时的开发中,创建一个对象最常用的方式是,使用new关键字调用类的构造函数来完成。我的问题是,什么情况下这种方式就不适用了,就需要采用建造者模式来创建对象呢?你可以先思考一下,下面我通过一个例子来带你看一下。

假设有这样一道设计面试题:我们需要定义一个资源池配置类ResourcePoolConfig。这里的资源池,你可以简单理解为线程池、连接池、对象池等。在这个资源池配置类中,有以下几个成员变量,也就是可配置项。现在,请你编写代码实现这个ResourcePoolConfig类。

图片

只要你稍微有点开发经验,那实现这样一个类对你来说并不是件难事。最常见、最容易想到的实现思路如下代码所示。因为maxTotal、maxIdle、minIdle不是必填变量,所以在创建ResourcePoolConfig对象的时候,我们通过往构造函数中,给这几个参数传递null值,来表示使用默认值。

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 (StringUtils.isBlank(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

现在,ResourcePoolConfig只有4个可配置项,对应到构造函数中,也只有4个参数,参数的个数不多。但是,如果可配置项逐渐增多,变成了8个、10个,甚至更多,那继续沿用现在的设计思路,构造函数的参数列表会变得很长,代码在可读性和易用性上都会变差。在使用构造函数的时候,我们就容易搞错各参数的顺序,传递进错误的参数值,导致非常隐蔽的bug。

// 参数太多,导致可读性差、参数可能传递错误
ResourcePoolConfig config = new ResourcePoolConfig("dbconnectionpool", 16, null, 8, null, false , true, 10, 20,false, true);

1
2
3

解决这个问题的办法你应该也已经想到了,那就是用set()函数来给成员变量赋值,以替代冗长的构造函数。我们直接看代码,具体如下所示。其中,配置项name是必填的,所以我们把它放到构造函数中设置,强制创建类对象的时候就要填写。其他配置项maxTotal、maxIdle、minIdle都不是必填的,所以我们通过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
40

接下来,我们来看新的ResourcePoolConfig类该如何使用。我写了一个示例代码,如下所示。没有了冗长的函数调用和参数列表,代码在可读性和易用性上提高了很多。

// ResourcePoolConfig使用举例
ResourcePoolConfig config = new ResourcePoolConfig("dbconnectionpool");
config.setMaxTotal(16);
config.setMaxIdle(8);

1
2
3
4
5

至此,我们仍然没有用到建造者模式,通过构造函数设置必填项,通过set()方法设置可选配置项,就能实现我们的设计需求。如果我们把问题的难度再加大点,比如,还需要解决下面这三个问题,那现在的设计思路就不能满足了。

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

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

  • 如果我们希望 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;
    }
  }
}

// 这段代码会抛出IllegalArgumentException,因为minIdle>maxIdle
ResourcePoolConfig config = new ResourcePoolConfig.Builder()
        .setName("dbconnectionpool")
        .setMaxTotal(16)
        .setMaxIdle(10)
        .setMinIdle(12)
        .build();

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
81
82
83



实际上,使用建造者模式创建对象,还能避免对象存在无效状态。我再举个例子解释一下。比如我们定义了一个长方形类,如果不使用建造者模式,采用先创建后set的方式,那就会导致在第一个set之后,对象处于无效状态。具体代码如下所示:

Rectangle r = new Rectange(); // r is invalid
r.setWidth(2); // r is invalid
r.setHeight(3); // r is valid

1
2
3
4

为了避免这种无效状态的存在,我们就需要使用构造函数一次性初始化好所有的成员变量。如果构造函数参数过多,我们就需要考虑使用建造者模式,先设置建造者的变量,然后再一次性地创建对象,让对象一直处于有效状态。

实际上,如果我们并不是很关心对象是否有短暂的无效状态,也不是太在意对象是否是可变的。比如,对象只是用来映射数据库读出来的数据,那我们直接暴露set()方法来设置类的成员变量值是完全没问题的。而且,使用建造者模式来构建对象,代码实际上是有点重复的,ResourcePoolConfig类中的成员变量,要在Builder类中重新再定义一遍。

# 与工厂模式有何区别?

从上面的讲解中,我们可以看出,建造者模式是让建造者类来负责对象的创建工作。上一节课中讲到的工厂模式,是由工厂类来负责对象创建的工作。那它们之间有什么区别呢?

实际上,工厂模式是用来创建不同但是相关类型的对象(继承同一父类或者接口的一组子类),由给定的参数来决定创建哪种类型的对象。建造者模式是用来创建一种类型的复杂对象,通过设置不同的可选参数,“定制化”地创建不同的对象。

网上有一个经典的例子很好地解释了两者的区别。

顾客走进一家餐馆点餐,我们利用工厂模式,根据用户不同的选择,来制作不同的食物,比如披萨、汉堡、沙拉。对于披萨来说,用户又有各种配料可以定制,比如奶酪、西红柿、起司,我们通过建造者模式根据用户选择的不同配料来制作披萨。

实际上,我们也不要太学院派,非得把工厂模式、建造者模式分得那么清楚,我们需要知道的是,每个模式为什么这么设计,能解决什么问题。只有了解了这些最本质的东西,我们才能不生搬硬套,才能灵活应用,甚至可以混用各种模式创造出新的模式,来解决特定场景的问题。

# 重点回顾

好了,今天的内容到此就讲完了。我们一块来总结回顾一下,你需要重点掌握的内容。

建造者模式的原理和实现比较简单,重点是掌握应用场景,避免过度使用。

如果一个类中有很多属性,为了避免构造函数的参数列表过长,影响代码的可读性和易用性,我们可以通过构造函数配合set()方法来解决。但是,如果存在下面情况中的任意一种,我们就要考虑使用建造者模式了。

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

  • 如果类的属性之间有一定的依赖关系或者约束条件,我们继续使用构造函数配合 set() 方法的设计思路,那这些依赖关系或约束条件的校验逻辑就无处安放了。

  • 如果我们希望创建不可变对象,也就是说,对象在创建好之后,就不能再修改内部的属性值,要实现这个功能,我们就不能在类中暴露 set() 方法。构造函数配合 set() 方法来设置属性值的方式就不适用了。

除此之外,在今天的讲解中,我们还对比了工厂模式和建造者模式的区别。工厂模式是用来创建不同但是相关类型的对象(继承同一父类或者接口的一组子类),由给定的参数来决定创建哪种类型的对象。建造者模式是用来创建一种类型的复杂对象,可以通过设置不同的可选参数,“定制化”地创建不同的对象。

# 课堂讨论

在下面的ConstructorArg类中,当isRef为true的时候,arg表示String类型的refBeanId,type不需要设置;当isRef为false的时候,arg、type都需要设置。请根据这个需求,完善ConstructorArg类。

 public class ConstructorArg {
    private boolean isRef;
    private Class type;
    private Object arg;
    // TODO: 待完善...
  }

1
2
3
4
5
6
7

欢迎留言和我分享你的想法,如果有收获,你也可以把这篇文章分享给你的朋友。

# 精选评论

点击查看

相逢是缘

打卡
一、使用场景:
1)类的构造函数必填属性很多,通过set设置,没有办法校验必填属性
2)如果类的属性之间有一定的依赖关系,构造函数配合set方式,无法进行依赖关系和约束条件校验
3)需要创建不可变对象,不能暴露set方法。
(前提是需要传递很多的属性,如果属性很少,可以不需要建造者模式)
二、实现方式:
把构造函数定义为private,定义public static class Builder 内部类,通过Builder 类的set方法设置属性,调用build方法创建对象。

三、和工厂模式的区别:
1)工厂模式:创建不同的同一类型对象(集成同一个父类或是接口的一组子类),由给定的参数来创建哪种类型的对象;
2)建造者模式:创建一种类型的复杂对象,通过很多可设置参数,“定制化”的创建对象
1
2
3
4
5
6
7
8
9
10
11
12

webmin

public class ConstructorArg {
    private boolean isRef;
    private Class type;
    private Object arg;

    public boolean isRef() {
        return isRef;
    }

    public Class getType() {
        return type;
    }

    public Object getArg() {
        return arg;
    }

    private ConstructorArg(Builder builder) {
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }

    public static class Builder {
        private boolean isRef;
        private Class type;
        private Object arg;

        public ConstructorArg build() {
            if(isRef &amp;&amp; type != null) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }

            if (!isRef &amp;&amp; type == null) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }

            if (this.isRef &amp;&amp; (arg != null &amp;&amp; arg.getClass() != String.class)) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }

            if (!this.isRef &amp;&amp; arg == null) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }

            return new ConstructorArg(this);
        }

        public Builder setRef(boolean ref) {
            if(ref &amp;&amp; this.type != null) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }
            this.isRef = ref;
            return this;
        }

        public Builder setType(Class type) {
            if (this.isRef || type == null) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }
            this.type = type;
            return this;
        }

        public Builder setArg(Object arg) {
            if (this.isRef &amp;&amp; (arg != null &amp;&amp; arg.getClass() != String.class)) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }

            if (!this.isRef &amp;&amp; arg == null) {
                throw new IllegalArgumentException(&#34;...&#34;);
            }
            this.arg = arg;
            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

Ken张云忠

public class ConstructorArg {
    private boolean isRef;
    private Class type;
    private Object arg;
    public ConstructorArg(ConstructorArgBuilder builder) {
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }
    public static class ConstructorArgBuilder {
        private boolean isRef;
        private Class type;
        private Object arg;
        public ConstructorArg builder() {
            if (arg == null) {
                throw new IllegalArgumentException(&#34;arg should not be null&#34;);
            }
            if (isRef == true) {
                if (arg instanceof String) {
                    type = String.class;
                } else {
                    throw  new IllegalArgumentException(&#34;when isRef is true,arg should be String type&#34;);
                }
            } else {
                type = arg.getClass();
            }
            return new ConstructorArg(this);
        }
        public ConstructorArgBuilder(boolean isRef) {
            this.isRef = isRef;
        }
        public ConstructorArgBuilder setArg(Object arg) {
            this.arg = arg;
            return this;
        }
    }
}
 // use case
ConstructorArg constructorArg = new ConstructorArgBuilder(true).setArg(0).builder();
ConstructorArg constructorArg1 = new ConstructorArgBuilder(false).setArg(1).builder();
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

黄林晴


PHP是世界上最好的需...


王涛


Frank

当在开发中需要创建一个具体的对象,如果必填属性很多,属性存在复杂的校验和属性之间存在依赖关系,可以使用建造者模式来避免类的构造函数参数列表过长,导致可读性差,不易使用的问题。建造者模式可以将类的构造方法私有,不提供类的setter方法,因此可以创建一个不变的对象。同时在某些场景下将属性构造好可以解决类的无效状态。
使用思路:把校验逻辑放置到 Builder 类中,先创建建造者,并且通过 set() 方法设置建造者的变量值,然后在使用 build() 方法真正创建对象之前,做集中的校验,校验通过之后才会创建对象。除此之外,我们把主类的构造函数为了private 私有权限,只能通过建造者来创建 类对象,并且主类没有提供任何 set() 方法,这样创建出来的对象就是不可变对象了。
1
2

LJK

感觉课后思考题的arguments逻辑判断相对复杂,再加上想尝试一下建造者模式,所以抛砖引玉,给一个Python的尝试,有一个困惑是对于Python这种语言,如何避免对用户暴露在调用builder之前build方法之前初始化的ConstructorArg对象?

class ConstructorArg(object):
    def __init__(self, isRef):  #如何避免暴露这个实例对象?
        self.isRef = isRef
        self.type = None
        self.arg = None
    
    def __repr__(self):
        string = f&#34;isRef:  {self.isRef}\n&#34; + \
                 f&#34;type:   {self.type}\n&#34; + \
                 f&#34;arg:    {self.arg}\n&#34;
        return string

    class ConstructorArgBuilder(object):
        def __init__(self, isRef):
            self.constructorArg = ConstructorArg(isRef)

        def addType(self, typeObj):
            self.constructorArg.type = typeObj
            return self

        def addArg(self, argObj):
            self.constructorArg.arg = argObj
            return self

        def build(self):
            if self.constructorArg.isRef:
                if self.constructorArg.type is None:
                    raise Exception(&#34;type cannot be None when isRef&#34;)
                elif not isinstance(self.constructorArg.type, str):
                    raise Exception(&#34;type must be string when isRef&#34;)
            elif not self.constructorArg.isRef:
                if self.constructorArg.type is None:
                    raise Exception(&#34;type cannot be None when not isRef&#34;)
                if self.constructorArg.arg is None:
                    raise Exception(&#34;arg cannot be None when not isRef&#34;)
            return self.constructorArg
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

朱晋君

课后思考题
public class ConstructorArg {

    private boolean isRef;
    private Class type;
    private Object arg;

    private ConstructorArg(Builder builder){
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }

    public static class Builder{

        private boolean isRef;
        private Class type;
        private Object arg;

        public Builder(boolean isRef){
            this.isRef = isRef;
        }

        public ConstructorArg build(){
            return new ConstructorArg(this);
        }

        public Builder setType(Class type) {
            if (!isRef &amp;&amp; null == type){
                throw new IllegalArgumentException(&#34;type must be not null&#34;);
            }
            this.type = type;
            return this;
        }

        public Builder setArg(Object arg) {
            if (isRef &amp;&amp; !(arg instanceof String)){
                throw new IllegalArgumentException(&#34;arg must be type of String&#34;);
            }

            if (!isRef &amp;&amp; null == arg){
                throw new IllegalArgumentException(&#34;arg must be not null&#34;);
            }
            this.arg = arg;
            return this;
        }
    }

    public static void main(String args[]){
        ConstructorArg constructorArg = new ConstructorArg.Builder(true).setArg(&#34;123&#34;).build();
    }
}
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

啦啦啦

用php实现了一个
&lt;?php
class ResourcePoolConfig{
    private $maxTotal;
    private $maxIdle;
    private $minIdle;
    public function __construct(build $build)
    {
        $this-&gt;maxTotal = $build-&gt;maxTotal;
        $this-&gt;maxIdle = $build-&gt;maxIdle;
        $this-&gt;minIdle = $build-&gt;minIdle;
        echo &#39;maxTotal&#39;.$this-&gt;maxTotal;
        echo &#39;&lt;br /&gt;&#39;;
        echo &#39;maxIdle&#39;.$this-&gt;maxIdle;
        echo &#39;&lt;br /&gt;&#39;;
        echo &#39;minIdle&#39;.$this-&gt;minIdle;
        echo &#39;&lt;br /&gt;&#39;;
    }
}

class Builder{
    public $maxTotal;
    public $maxIdle;
    public $minIdle;
    public function noodleValidate(){
        if($this-&gt;maxIdle&gt;$this-&gt;maxTotal){
            throw new Exception(&#34;maxIdle抛出异常&#34;);
        }
        if($this-&gt;minIdle&gt;$this-&gt;maxTotal){
            throw new Exception(&#34;minIdle抛出异常&#34;);
        }
    }

    public function setMaxTotal($value=20){
        $this-&gt;maxTotal = $value;
        return $this;
    }

    public function setMaxIdle($value=10){
        $this-&gt;maxIdle = $value;
        return $this;
    }

    public function setMinIdle($value=10){
        $this-&gt;minIdle = $value;
        return $this;
    }
}

$b = new Builder();
$b-&gt;setMaxTotal(5)-&gt;setMaxIdle()-&gt;setMinIdle()-&gt;noodleValidate();
new ResourcePoolConfig($b);
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

Algo

package com.acacia.leetcode.huahua.questions;

public class ConstructorArg {
    private boolean isRef;
    private Class type;
    private Object arg;

    private ConstructorArg(Builder builder){
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }

    public static class Builder{
        private final static Class TYPE_STRING = String.class;
        private final static Object ARG_STRING = &#34;String&#34;;

        private boolean isRef;
        private Class type;
        private Object arg;

        public ConstructorArg build(){
            if (isRef == true){
                this.type = TYPE_STRING;
                this.arg = ARG_STRING;
                return new ConstructorArg(this);
            }else {
                return new ConstructorArg(this);
            }
        }

        public Builder setRef(boolean ref) {
            this.isRef = ref;
            return this;
        }

        public Builder setType(Class type) {
//            if (!type.isMemberClass()){
//                throw new IllegalArgumentException(&#34;failed class name&#34;);
//            }
            this.type = type;
            return this;
        }

        public Builder setArg(Object arg) {
            if (arg == null){
                throw new IllegalArgumentException(&#34;can not be null&#34;);
            }
            this.arg = arg;
            return this;
        }
    }

    public static void main(String[] args) {
        ConstructorArg arg = new ConstructorArg.Builder().setRef(true).build();
        System.out.println(arg.type);
        System.out.println(arg.arg);
        ConstructorArg arg1 = new ConstructorArg.Builder().setArg(false).setType(Integer.class).setArg(2).build();
        System.out.println(arg1.type);
        System.out.println(arg1.arg);
    }
}




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

cricket1981

public class ConstructorArg {

    private boolean isRef;
    private Class type;
    private Object arg;

    private ConstructorArg(Builder builder) {
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }

    public boolean getIsRef() {
        return isRef;
    }

    public Class getType() {
        return type;
    }

    public Object getArg() {
        return arg;
    }

    public static class Builder {

        private boolean isRef;
        private Class type;
        private Object arg;

        public ConstructorArg build() {
            if (arg == null) {
                throw new IllegalArgumentException(&#34;The value of parameter `arg` should be provided.&#34;);
            }
            if (!this.isRef &amp;&amp; type == null) {
                throw new IllegalArgumentException(&#34;The value of parameter `type` should be provided if `isRef` == false.&#34;);
            }
            return new ConstructorArg(this);
        }

        public Builder setRef(boolean isRef) {
            this.isRef = isRef;
            return this;
        }

        public Builder setType(Class type) {
            this.type = type;
            return this;
        }

        public Builder setArg(Object arg) {
            this.arg = arg;
            return this;
        }
    }

}

用法:
ConstructorArg constructorArg1 = new ConstructorArg.Builder()
        .setArg(&#34;rateCounter&#34;)
        .setRef(true)
        .build();

ConstructorArg constructorArg2 = new ConstructorArg.Builder()
        .setArg(&#34;127.0.0.1&#34;)
        .setType(String.class)
        .setRef(false)
        .build();
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

小晏子

课后讨论题:

 public class ConstructorArg {
    private boolean isRef;
    private Class type;
    private Object arg;
    // TODO: 待完善...

    private ConstructorArg(Builder builder) {
        this.isRef = builder.isRef;
        this.type  = builder.type;
        this.arg   = builder.arg;
    }

    public static class Builder {
        private boolean isRef;
        private Class type;
        private Object arg;

        public ConstructorArg build() {
            if (!isRef) {
                if (type == null || arg == null){
                    throw new IllegalArgumentException(&#34;type and arg must be set when isRef is false&#34;)
                }
            } else {
                if (!(arg instanceof String)) {
                    throw new IllegalArgumentException(&#34;arg must be a String instance when isRef is true&#34;)
                }
            }
            return new ConstructorArg(this);
        }
    }

    public Builder setIsRef(boolean isRef){
        this.isRef = isRef;
        return this;
    }

    public Builder setType(Class type) {
        this.type = type;
        return this;
    }

    public Builder setObject(Object arg) {
        this.arg = arg;
        return this;
    }
  }

  //use case
  ConstructorArg ca = ConstructorArg.Builder()
        .setIfRef(false)
        .setType(Integer)
        .setObject(2)
        .build();
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

javaadu

课堂讨论题:

/**
 * 在下面的 ConstructorArg 类中,
 * 当 isRef 为 true 的时候,arg 表示 String 类型的 refBeanId,type 不需要设置;
 * 当 isRef 为 false 的时候,arg、type 都需要设置
 *
 * @author javaadu
 */
public class ConstructorArg {
    private boolean isRef;
    private Class type;
    private Object arg;

    private ConstructorArg(Builder builder) {
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }

    public static class Builder {
        private boolean isRef;
        private Class type;
        private Object arg;

        public ConstructorArg build() {
            if (arg == null) {
                throw new IllegalArgumentException(&#34;arg必须设置&#34;);
            }
            if (isRef) {
                if (!(arg instanceof String)) {
                    throw new IllegalArgumentException(&#34;arg必须为String类型的对象&#34;);
                }
            } else {
                if (type == null) {
                    throw new IllegalArgumentException(&#34;arg必须设置&#34;);
                }
            }

            return new ConstructorArg(this)
        }

        public Builder setRef(boolean ref) {
            isRef = ref;
            return this;
        }

        public Builder setArg(Object arg) {
            this.arg = arg;
            return this;
        }

        public Builder setType(Class type) {
            this.type = type;
            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

Jeff.Smile

建造者模式核心代码:
ResourcePoolConfig config = new ResourcePoolConfig.Builder()
        .setName(&#34;dbconnectionpool&#34;)
        .setMaxTotal(16)
        .setMaxIdle(10)
        .setMinIdle(12)
        .build();
1
2
3
4
5
6
7

不似旧日

笔记:
一、使用场景:
1)类的构造函数必填属性很多,通过set设置,没有办法校验必填属性
2)如果类的属性之间有一定的依赖关系,构造函数配合set方式,无法进行依赖关系和约束条件校验
3)需要创建不可变对象,不能暴露set方法。
(前提是需要传递很多的属性,如果属性很少,可以不需要建造者模式)
二、实现方式:
把构造函数定义为private,定义public static class Builder 内部类,通过Builder 类的set方法设置属性,调用build方法创建对象。

三、和工厂模式的区别:
1)工厂模式:创建不同的同一类型对象(集成同一个父类或是接口的一组子类),由给定的参数来创建哪种类型的对象;
2)建造者模式:创建一种类型的复杂对象,通过很多可设置参数,“定制化”的创建对象
1
2
3
4
5
6
7
8
9
10
11
12

墨雨


李小四

设计模式_46:
# 作业
1
2

public void build () {         if (isRef && arg == null) throw new IllegalArgumentException("...");                  if (isRef && !arg instanceof String) throw new IllegalArgumentException("...");                  if (!isRef && arg == null) throw new IllegalArgumentException("...");                  if (!isRef && type == null) throw new IllegalArgumentException("...");                  if (!isRef && !arg instanceof type) throw new IllegalArgumentException("...");         //...     }


# 感想
一直不是很清楚哪种场景必须用*Builder*模式,常常感觉用不用都可以。今天的总结的四个因素非常认同(请原谅我复读机了):
    - 必须的参数太多,构造函数太长
    - 成员之间有依赖关系,需要一个地方来检测(也就是*build()*方法内)
    - 想实现final效果
    - 避免对象的无效状态
1
2
3
4
5
6
7

守拙


public class ConstructorArg {
    private static final String TAG = &#34;ConstructorArg&#34;;

    private boolean isRef;
    private Class type;
    private Object arg;

    private ConstructorArg(Builder builder){
        this.isRef = builder.isRef;
        this.type = builder.type;
        this.arg = builder.arg;
    }

 

    public static class Builder{
        private boolean isRef;
        private Class type;
        private Object arg;

        public Builder(boolean isRef){
            this.isRef = isRef;
        }

        public Builder setType(Class type){
            this.type = type;
            return this;
        }

        public Builder setArg(Object arg){
            this.arg = arg;
            return this;
        }

        public ConstructorArg build(){
            checkIsRef(this.isRef);
            ConstructorArg arg = new ConstructorArg(this);
            return arg;
        }

        /**校验参数*/
        private void checkIsRef(boolean isRef){
            /**
             * 当 isRef 为 true 的时候,arg 表示 String 类型的 refBeanId,type 不需要设置;*/
            if (this.isRef == true){
                if (this.type != null){
                    throw new IllegalArgumentException(&#34;当 isRef 为 true 的时候,type 不需要设置;&#34;);
                }

                if (!(this.arg instanceof String)){
                    throw new IllegalArgumentException(&#34;当 isRef 为 true 的时候,arg 表示 String 类型的 refBeanId&#34;);
                }
            }

            /**
             * 当 isRef 为 false 的时候,arg、type 都需要设置。*/
            if (this.isRef == false){
                if (this.arg == null){
                    throw new IllegalArgumentException(&#34;当 isRef 为 false 的时候,arg需要设置。&#34;);
                }

                if (this.type == null){
                    throw new IllegalArgumentException(&#34;当 isRef 为 false 的时候,type 都需要设置。&#34;);
                }
            }
        }
    }
}
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

传说中的成大大

感觉建造者模型就是对创建过程的一个封装
1

#极客时间
上次更新: 2025/06/04, 15:06:15
工厂模式(下):如何设计实现一个DependencyInjection框架?
原型模式:如何最快速地clone一个HashMap散列表?

← 工厂模式(下):如何设计实现一个DependencyInjection框架? 原型模式:如何最快速地clone一个HashMap散列表?→

最近更新
01
AIIDE
03-07
02
githubActionCICD实战
03-07
03
windows安装Deep-Live-Cam教程
08-11
更多文章>
Theme by Vdoing
总访问量 次 | 总访客数 人
| Copyright © 2021-2025 ggball | 赣ICP备2021008769号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×

评论

  • 评论 ssss
  • 回复
  • 评论 ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
  • 回复
  • 评论 ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
  • 回复
×