gpt4 book ai didi

java - Java 中的不变参数

转载 作者:行者123 更新时间:2023-11-29 06:58:04 24 4
gpt4 key购买 nike

我正在阅读 Bloch 的 Effective Java,现在我在阅读第 2 项(构建器模式)。这是他说的:

Like a constructor, a builder can impose invariants on its parameters. The build method can check these invariants.

不变量是什么意思?你不能解释一下吗?

最佳答案

不变量是简单的约束,为了使对象处于安全状态,不应违反这些约束。

不变量可以很简单,比如

simple regex check on some string property of a class. 

它可以是一个复杂的/组合的不变量,这意味着两个参数组合成一个有效的组合。例如。 -

A class can hold type of animal and type of sound it produces.
so , a combination of dog and bark is valid but a combination of dog and meow is not valid. (just a case)

对于简单的情况,构建器可以在构建器的相应属性方法中检查不变量本身,如果它接受任何具有不变量的此类参数,甚至可以在构建器的构造函数中检查不变量。

对于组合不变量,可以在内部具有构建器的类的构造函数中进行检查。或者,builder 的 build 方法也可以做所有这些组合不变性验证。

我希望这对概念有所帮助。

关于java - Java 中的不变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com