How to add set/get methods methods in class constructor
8 次查看(过去 30 天)
显示 更早的评论
I have a class with some properties that are linked to a registry. I would like the class to automatically retrieve values from the registry anytime one of those properties is accessed; conversely, I would like to push those values to a registry anytime a value is modified by the program. Rather than define each set/get method individually, I would like to set these set/get methods during the class constuctor. Some pseduocode is defined below:
classdef ExampleClass < handle
properties(SetObservable,GetObservable)
prop1;
prop2;
prop3; %etc.
end
methods
function obj = ExampleClass(varargin)
obj.registry = Registry(); %Defined elsewhere
proplist = fields(obj);
for ii = 1:length(proplist), SomeFuntionToAddSetMethod(obj,proplist{ii}, @obj.ListenerPullValues); end
for ii = 1:length(proplist), SomeFuntionToAddGetMethod(obj,proplist{ii}, @obj.ListenerPushValues); end
end
end
methods(Access = private)
function ListenerPushValues(obj,eventData,~)
obj.registry.WriteValue(eventData.Name,obj.(eventData.Name)); %write value in registry
end
function ListenerPullValues(obj,eventData,~)
obj.(eventData.Name) = obj.registry.ReadValue(eventData.Name); %read value in registry
end
end
end
Question
Is it possible to assign set/get functions in the class constructor?
0 个评论
回答(3 个)
Sean de Wolski
2021-4-6
You want dependent properties: Set and Get Methods for Dependent Properties - MATLAB & Simulink (mathworks.com)
Steven Lord
2021-4-6
If prop1, prop2, prop3, etc. are properties in this Registry object that you want to expose as properties of the ExampleClass class, take a look at dynamic properties.
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!