How to order events triggered by overvable parameters?

2 Ansichten (letzte 30 Tage)
Pascal
Pascal am 3 Jul. 2014
Beantwortet: Pascal am 30 Jul. 2014
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:
  1. Listening to the 'PostSet' event does not work because it is triggered after the call to draw.
  2. Triggering a custom even in set.param before the call to draw is not allowed, only standard event are allowed in set/get methods.
  3. 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.
  4. 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?

Akzeptierte Antwort

Pascal
Pascal am 30 Jul. 2014
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.

Weitere Antworten (0)

Kategorien

Mehr zu Migrate GUIDE Apps finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by