Add a event callback across all instances of class??
5 次查看(过去 30 天)
显示 更早的评论
The idea is as follows:
If a property of an instance of class is changed, then all the instances of this class should take this property and do some update. The problem is I don't know how many instances of class exist, so I thought using event and listener could be a solution. Here is my code:
classdef myclass < handle
%EVENTTAKER Summary of this class goes here
% Detailed explanation goes here
properties
hf
sharedProp
end
events
sharedPropChanged
end
methods
function obj = myclass()
obj.sharedProp = rand(100, 2); % define prop as random data
obj.hf = figure;
plot(obj.sharedProp);
addlistener(obj,'sharedPropChanged',@obj.listenerCallback);
end
function setSharedProp(obj, newProp)
obj.sharedProp = newProp;
% broadcast event to all objects of class
notify(obj, 'sharedPropChanged');
end
function listenerCallback(obj, srcObj, ~)
obj.sharedProp = srcObj.sharedProp;
obj.update();
end
function update(obj)
plot(obj.sharedProp);
end
end
end
To test:
o1 = myclass; o2 = myclass;
o1.setSharedProp(rand(10, 2))
The result is that only the first instance get update, the second not.
Is this a plausible solution, or there is any way to implement this?
Thnks
0 个评论
采纳的回答
Guillaume
2015-7-28
编辑:Guillaume
2015-7-28
What you're trying to create is a static property (belongs to the class not the instances). Matlab does not have that, but you could possibly emulate it with a constant property holding a reference to a handle class. Either make a lightweight handle class to wrap your static property or simply use a containers.Map with only one key:
classdef classwithstaticprop < handle
properties (Constant, GetAccess = private)
staticprop = containers.Map; %or just make a lightweight handle class
end
properties (Dependent)
sharedprop
end
methods
function this = classwithstaticprop() %constructor
if length(this.staticprop) == 0 %#ok<ISMT> isempty not defined for map
%first instance, initialise;
m = this.staticprop; %you have to use a local variable, see the doc
m('prop') = 1; %#ok<NASGU> %initialise to default value
end
end
function set.sharedprop(this, value)
m = this.staticprop;
m('prop') = value; %#ok<NASGU> %it's a handle
end
function value = get.sharedprop(this)
value = this.staticprop('prop');
end
end
end
See this page for why you have to use a local variable when changing the value of the handle class referred by the constant property.
6 个评论
Guillaume
2015-7-28
Nor can you put classes in private folders, which would be another way of limiting the visibility of the utility class.
Steven Lord
2015-7-28
You cannot place multiple classes in the same file.
You cannot place class files in private folders.
You CAN place class files in package directories, however.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Class File Organization 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!