Turns out, the cleaner way I have found is to get rid of build_in set/get methods entirely. Their restrictions make them a liability when your class starts getting more complicated or is being derived from. Using custom set_/get_ methods enables to add custom callbacks and dependencies to other variables at will, while keeping the property private. The obvious drawback is that get/set events must be redefined.
How to order events triggered by overvable parameters?
2 次查看(过去 30 天)
显示 更早的评论
I have a class displaying a figure that depends on a parameter. Each time the parameter is changed, the figure has to be redrawn. My code looks like this:
classdef Foo < handle
properties (SetObservable, AbortSet)
param
end
methods
function set.param(obj, param)
obj.param = param
obj.draw()
end
function draw(obj)
% draw stuff
end
end
end
This works fine. However, I would like to be able to add subclasses of Foo that prepare other things to be displayed when param is changed. This needs to happen before the call to draw. Now I am wondering how to do that as cleanly as possible. Here is what I tried and why it doesn't work:
- Listening to the 'PostSet' event does not work because it is triggered after the call to draw.
- Triggering a custom even in set.param before the call to draw is not allowed, only standard event are allowed in set/get methods.
- Setting up 'draw' as a callback on 'PostSet' does not work because callbacks cannot be ordered. In fact, it is specified that callbacks are called synchronously.
- My current "least-evil"solution is to add another function called set_param:
classdef Foo < handle
properties (SetObservable, AbortSet, SetAccess=protected)
param
end
methods
function set.param(obj, param)
obj.param = param
end
function set_param(obj, param)
obj.param = param
obj.draw()
end
function draw(obj)
% draw stuff
end
end
end
One minor draw back is that I need to call obj.set_param(param) instead of obj.param = param. One major drawback is that child classes still have access to set.param and therefore may erroneously call obj.param = param instead of obj.set_param. Indeed, if param is set to SetAccess=private, the child class cannot add listeners to that property.
Any idea of a better solution?
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!