这是一个基本实现。每个对象都有一个父对象和一个子对象数组。使用
subsasgn
,我们可以更改对象及其子对象的属性,因为该对象是单向的,所以不希望更改父对象的属性。
用法:
a = oneway(1,2);
b = oneway(a);
c = oneway(b);
如果我们设置
a.prop1 = 7;
,那么
b
将被改变,从而导致
c
的改变。如果你只想改变直接子元素,你可以取消注释第
31
行并注释第
30
行。
classdef oneway < handle
properties
parent
children={};
end
properties
prop1
prop2
end
methods
function obj = oneway(varargin)
if nargin == 1
a = varargin{1};
if isa(a,'oneway')
obj.prop1 = a.prop1;
obj.prop2 = a.prop2;
obj.parent = a;
a.children{end+1} = obj;
end
elseif nargin == 2
obj.prop1 = varargin{1};
obj.prop2 = varargin{2};
end
end
function obj = subsasgn(self, S, B)
if strcmp(S.type, '.')
if ismember(S.subs, properties(self))
obj = builtin('subsasgn', self, S, B);
for k = 1: numel(self.children)
self.children{k} = subsasgn(self.children{k},S,B);
end
end
end
end
function delete(self)
self.parent.children (cellfun(@(x)x==self,self.parent.children))=[];
for k = 1: numel(self.children)
self.children{k}.parent =[];
end
end
end
end