linking properties in object oriented code

1 ビュー (過去 30 日間)
nathan blanc
nathan blanc 2021 年 5 月 14 日
回答済み: TADA 2021 年 8 月 29 日
I have an object oriented code where I want to be able to link several properties in several manners. e.g. "these properties are always equal", "these properties maintain a ratio of 5" etc. these are not properites of the same object, and sometimes not of objects from the same class.
I was thinking of using linkprop but it is not recommended for objects other than graphic objects. also to the best of my knowledge it can only link properties as equal.
I was thinking of adding postset listeners to the properties where the callback function changes the other properties accordingly, but I am not sure how to prevent recursive calling. i.e one function changes the other property changing the first one etc.
would be thankfull for any assistance
Nathan

採用された回答

TADA
TADA 2021 年 8 月 29 日
it is possible using Post set events.
I am working on an MVVM toolbox which relies on post set events (TaDuAs/Flow: Framework for matlab (github.com))
heres an example which uses a similar notion
The attachment has 3 classes:
ObjectA - a generic handle class with set-observable properties
PropertyBinding - represents a single bound object, its property and an update function
PropertyBinder - manages the bindings for a list of objects.
How to use:
% a simple binding example which copies the values of specified proeprties
% between the objects in the list.
list = {ObjectA(), ObjectA(), ObjectA()};
props = {'X', 'X', 'Y'};
pb = PropertyBinder(list, props);
list{1}.X = 100;
list{1}
ans =
ObjectA with properties: X: 100 Y: [] Z: []
list{2}
ans =
ObjectA with properties: X: 100 Y: [] Z: []
list{3}
ans =
ObjectA with properties: X: [] Y: 100 Z: []
% a more complex relationship, where some of the bindings copy the value
% as-is and some alter the copied value
list2 = {ObjectA(), ObjectA(), ObjectA()};
props2 = {'X', 'X', 'Y'};
pb2(1) = PropertyBinder(list([1,3]), props([1,3]), {@(x) x/5, @(x) x*5});
pb(2) = PropertyBinder(list([2,3]), props([2,3]), {@(x) x/5, @(x) x*5})
pb =
1×2 PropertyBinder array with properties: Bindings Listeners
pb(3) = PropertyBinder(list(1:2), props(1:2));
list{1}.X = 100;
list{1}
ans =
ObjectA with properties: X: 100 Y: [] Z: []
list{2}
ans =
ObjectA with properties: X: 100 Y: [] Z: []
list{3}
ans =
ObjectA with properties: X: [] Y: 500 Z: []

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by