静电
R6 类可以利用 environment 的按引用拷贝行为在对象之间共享字段。要实现这一点,请定义名为 shared 的私有字段。该字段的定义需要多行代码。它应当:
- 创建一个新的 environment。
- 将任何需要共享的字段赋值到该 environment 中。
- 返回该 environment。
共享字段应通过活动绑定(active binding)访问。它们与您之前见过的其他活动绑定相同,但使用 private$shared$ 前缀来读取这些字段。
R6Class(
"Thing",
private = list(
shared = {
e <- new.env()
e$a_shared_field <- 123
e
}
),
active = list(
a_shared_field = function(value) {
if(missing(value)) {
private$shared$a_shared_field
} else {
private$shared$a_shared_field <- value
}
}
)
)
请注意,活动绑定的名称必须与您希望获取或设置的共享字段名称相同;在上面的示例中它们都是 a_shared_field。
本练习是课程的一部分
R 中的 S3 与 R6 面向对象编程
练习说明
已为您部分定义了一个 MicrowaveOven 类。
- 在
MicrowaveOven类的 private 元素中,更新名为shared的字段。- 该字段应包含用花括号
{}包裹的 3 行代码。 - 首先调用
new.env()(文档)创建一个名为e的新 environment,然后… - 向
e中赋值一个名为safety_warning的变量,取值为"Warning. Do not try to cook metal objects.",然后… - 返回该 environment。
- 该字段应包含用花括号
- 添加一个名为
safety_warning的活动绑定,用于获取或设置私有共享的safety_warning字段。- 在
active元素中将其定义为一个函数。 - 它只接受一个名为
value的参数。 - 它应获取或设置
private$shared$safety_warning。
- 在
- 分别创建两个
MicrowaveOven对象,命名为a_microwave_oven和another_microwave_oven。 - 将
a_microwave_oven上的safety_warning字段更改为"Warning. If the food is too hot you may scald yourself."。 - 查看
another_microwave_oven上的safety_warning字段,确保它已经被更改。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Complete the class definition
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
shared = {
# Create a new environment named e
___
# Assign safety_warning into e
___
# Return e
___
}
),
active = list(
# Add the safety_warning binding
safety_warning = ___(___) {
if(___(___)) {
___
} else {
___ <- ___
}
}
)
)
# Create two microwave ovens
a_microwave_oven <- ___
another_microwave_oven <- ___
# Change the safety warning for a_microwave_oven
___ <- "Warning. If the food is too hot you may scald yourself."
# Verify that the warning has change for another_microwave
___