【发布时间】:2011-06-25 01:59:56
【问题描述】:
我有一个类有一些依赖的属性,但我真的只想计算一次。
我刚刚得出结论,在 MATLAB 中对依赖类属性使用惰性求值要么是不可能的,要么是个坏主意。最初的计划是为每个需要更新的(公共)属性设置一个私有逻辑标志,并让构造函数将其设置为 true。然后,当调用属性访问器时,它会检查该标志并计算值并仅在需要时将其存储(在另一个私有属性中)。如果标志为假,它只会返回缓存值的副本。
我认为困难在于对属性访问器的限制,即它们不理会其他不相关的属性。换句话说,get.property(self) 方法不能改变 self 对象的状态。有趣的是,这在我目前的课程中默默地失败了。 (即get.方法中既没有设置更新标志也没有设置缓存的计算结果,所以每次都运行昂贵的计算。
我怀疑将惰性属性从公共依赖属性更改为具有公共 GetAccess 但私有 SetAccess 的方法会起作用。但是,我不喜欢以这种方式欺骗属性约定。我希望只有一个“惰性”属性可以为我做这一切。
我是否遗漏了一些明显的东西? MATLAB 中依赖类属性的访问器方法是否禁止更改类实例的状态?如果是这样,那么定义什么相当于具有私有副作用的访问器是获得我想要的行为的最不邪恶的方式吗?
编辑:这是一个测试类...
classdef LazyTest
properties(Access = public)
% num to take factorial of
factoriand
end
properties(Access = public, Dependent)
factorial
end
properties(Access = private)
% logical flag
do_update_factorial
% old result
cached_factorial
end
methods
function self = LazyTest(factoriand)
self.factoriand = factoriand;
self.do_update_factorial = true;
end
end
methods
function result = get.factorial(self)
if self.do_update_factorial
self.cached_factorial = factorial(self.factoriand);
% pretend this is expensive
pause(0.5)
self.do_update_factorial = false
end
result = self.cached_factorial;
end
end
end
用
运行它close all; clear classes; clc
t = LazyTest(3)
t.factorial
for num = 1:10
tic
t.factoriand = num
t.factorial
toc
end
从handle继承后,时间大幅下降。
【问题讨论】:
标签: oop matlab properties lazy-evaluation accessor