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!