什么是后继价值模式

unl*_*udo 1 design-patterns scala

我正在阅读scala in action(manning edition),并且有一个关于此模式的章节,其中包含一个代码示例:

class PureSquare(val side: Int) {
def newSide(s: Int): PureSquare = new PureSquare(s)
def area = side * side
}
Run Code Online (Sandbox Code Playgroud)

这本书有一个链接应该解释模式.不幸的是,链接被破坏了,我找不到它.

有人能够解释这种模式以及这段代码应该如何工作?

因为在调用区域函数时我没有看到如何调用newSide.

谢谢

pag*_*_5b 5

你是对的:newSide不直接改变area,但它创造了PureSquare一个不同side长度的新.

它旨在展示如何使用纯功能对象(没有可变的内部状态),同时满足在我们的程序中进行更改的需要

使用此模式您创建的任何对象在技术上仍然是不可变的,但您可以通过调用正确的方法(在本例中newSide)"模拟"更改对象

一个值得100个解释的例子

val square1 = new PureSquare(1)
assert(square1.area == 1)

//this is similar to changing the side of square1
val square2 = square1.newSide(2)

//and the area changes consequently
assert(square2.area == 4)
//while the original call is still referentially transparent [*]
assert(square1.area == 1)
Run Code Online (Sandbox Code Playgroud)

[*] http://en.wikipedia.org/wiki/Referential_transparency_(computer_science)

  • @unludo但任何引用旧版本的内容都不会发生变化.这实际上被视为一件好事,因为它允许合理的并发性,避免同步死锁等. (2认同)