我與依賴幾個屬性的類,但我真的想只有一次計算。MATLAB懶評價相依性
我只是得出結論,使用在MATLAB依賴類屬性懶惰的評價是不可能的或者是一個壞主意。最初的計劃是爲需要更新的每個(公共)屬性設置專用邏輯標誌,並讓構造函數將其設置爲true。然後,當屬性訪問器被調用時,它將檢查該標誌並計算該值並僅在需要時將其存儲(在另一個私有屬性中)。如果該標誌是假的,它只會返回一個緩存值的副本。
我相信困難在於對屬性訪問的限制,也就是說,他們先不談其他無關的特性。換句話說,get.property(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
繼承後的時間顯着下降。
這似乎是訣竅。 – 2011-02-10 19:07:50