- SetObservable, GetObservable - https://www.mathworks.com/help/matlab/matlab_oop/property-attributes.html
- addlistener - https://www.mathworks.com/help/matlab/ref/handle.addlistener.html
- Listen for Changes to Property Values - https://www.mathworks.com/help/matlab/matlab_oop/listening-for-changes-to-property-values.html
Common get and set methods for dynamic properties in user defined classes
3 次查看(过去 30 天)
显示 更早的评论
The matlab documentation shows how to define get and set functions for dynamic properties. Is it possible to defiine get and set methods that are common to several dynamic properties?
0 个评论
回答(1 个)
Paras Gupta
2023-10-16
编辑:Paras Gupta
2023-10-16
Hi Rajmohan,
I understand that you are want to have common set and get methods for several dynamic properties in a MATLAB class.
You can use the 'addlistener' function along with the 'PostSet' event to define a common set method, and the 'addlistener' function with the 'PostGet' event to define a common get method.
The following example code illustrates how to achieve the same:
classdef Car1 < handle
% The properties need to be defined as SetObservable and GetObservable
properties (SetObservable, GetObservable)
Brand
Model
end
methods
function obj = Car1(brand, model)
obj.Brand = brand;
obj.Model = model;
addlistener(obj, 'Brand', 'PostSet', @obj.commonSetMethod);
addlistener(obj, 'Model', 'PostSet', @obj.commonSetMethod);
addlistener(obj, 'Brand', 'PostGet', @obj.commonGetMethod);
addlistener(obj, 'Model', 'PostGet', @obj.commonGetMethod);
end
function commonSetMethod(obj, ~, ~)
disp('Common set method called');
end
function commonGetMethod(obj, ~, ~)
disp('Common get method called')
end
end
end
You can try running the following commands to see that the 'commonSetMethod' and 'commonGetMethod' are being executed for both the properties 'Brand' and 'Model'.
car = Car1('Brand1', 'Model1');
car.Brand = 'Brand2';
car.Model = 'Model2'
disp(car.Brand);
disp(car.Model);
Please refer to the following documentation links for more information on the functions used in the code above:
Hope this resolves your query.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Guidance, Navigation, and Control (GNC) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!