java - 不可变模式要求
问题描述
我正在使用 java 研究不可变模式,但我无法理解以下两个要求:
- 访问属性的实例方法不得更改实例变量
- 确保不可变类的构造函数是唯一设置或修改实例变量值的地方。
请有人为第一点举一个简单的例子。对于第二点,我不明白我们如何通过构造函数修改变量,而它们是最终的?
解决方案
这两点或多或少说的是同一件事。它们只是意味着,一旦对象被初始化,就不应更改它。
对于一个真正不可变的对象,那么每个对象都是引用也必须不能被访问器方法修改。例如,String
该类由char[]
可变的 a 支持。但是,String
该类没有公开任何可以让您更改其支持数组内容的方法。因此,String
该类可以被认为是不可变的。
关于最终变量——变量必须能够设置在某个地方。拥有一个您根本无法设置的最终变量并没有多大用处。所以构造函数是特殊的,允许设置标记为final的变量。
class StringArrayList {
// make the variable private, to protect it from being modified from outside the class
private final String[] arr;
StringArrayList(int size) {
// constructors are the only method allowed to set final variables
arr = new String[size];
}
String get(int i) {
// get method doesn't change the state of the object, so is fine
// However, if the object returned is mutable then there might be issues.
return arr[i];
}
void set(int i, String item) {
// set changes the state of arr, and so with this method, StringArrayList cannot
// be considered immutable
arr[i] = item;
}
}
推荐阅读
- javascript - 尝试设置联系表并收到错误 404
- ruby-on-rails - 尝试将表单保存到数据库时出现错误未初始化常量(Ruby on Rails)
- javascript - 选择其他选项时按钮不断重复
- javascript - 如何将函数作为道具传递给子组件并在Vue中从那里调用它?
- python - 响应对象不返回我想从 URL 中抓取的数据
- python - python函数计算成绩
- php - 连续更新值 PHP/MySql
- javascript - 向下滚动页面时自定义光标消失
- c++ - 如何比较 C/C++ 中的数组元素?
- c# - 在 ASP.NET CORE 中使用 EF 插入 ID 时出现 SQL 错误