How to synchronise inherited properties of class
1 回表示 (過去 30 日間)
古いコメントを表示
I have a superclass TubeClass with a number of properties, one of which is outsideDiameter. From this superclass, I derive two subclasses, StraightTubeClass and BentTubeClass. Both of these classes inherit the property outsideDiameter. So far so good...
I would now like to create a third class, UTubeClass, which again inherets from TubeClass. Now, UTubeClass comprises two straight legs of tube and a 180° bend. It also inherits the outsideDiameter property. So now I have a construction something like
MyUTube = UTubeClass; % Make new U-tube object
MyUTube.outsideDiameter = 100
MyUTube.someOtherProperties = 'foo'
MyUTube.straightLeg.outsideDiameter = 100
MyUTube.bend.outsideDiameter = 100
Ideally the outsideDiameter property would be the same in all places. I can figure out how to create a set method for UTubeClass such that when I set the property of outside diameter it is synchronised across all three usages, eg
MyUTube = UTubeClass;
MyUTube.outsideDiameter = 500;
% results in...
MyUTube.outsideDiameter = 500
MyUTube.straightLeg.outsideDiameter = 500
MyUTube.bend.outsideDiameter = 500
However, it is still possible to break this and independently set the value of the straight leg or bend outside diameter, eg
MyUTube = UTubeClass;
MyUTube.outsideDiameter = 500;
% results in...
MyUTube.outsideDiameter = 500
MyUTube.straightLeg.outsideDiameter = 500
MyUTube.bend.outsideDiameter = 500
% however...
MyUTube.straightLeg.outsideDiameter = 1000; % makes no sense, because now the OD is out of synch with the other values
So, is there a way to prevent this behavour, or should I be approaching the problem differently.
0 件のコメント
採用された回答
Jeff Miller
2019 年 10 月 15 日
I would say your UTubeClass should not descend from TubeClass. It's not the case that UTube "is a" Tube, but rather than UTube "has a" tube (or, really, it has two of them--one bent and one straight).
Another way to say it is that the UTube does not have its own independent diameter, separately from the diameters of its component straight and bent tubes, so there shouldn't be a separate property for UTube.outsideDiameter.
2 件のコメント
Steven Lord
2019 年 10 月 15 日
Indeed. The way I'd probably implement this is by giving UTubeClass properties that contain (as you said, has-a versus is-a) a StraightTube and a BentTube. The property set methods for those properties would validate that they have compatible outsideDiameter values.
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!