Add a event callback across all instances of class??
조회 수: 6 (최근 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에서 Properties에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!