Object composition and property updating
显示 更早的评论
I'm struggling with an implementation of Matlab's OOP and object composition. For simplicity I'll use a car example. Im constructing a of series classes. One is a kind of Master class (like a car) and a series of other classes, (tire, window, door, etc). When I give the car properties using said objects, I'm having trouble updating the properties of the car parts. If for example a property of the car changes AND that change affects its tire property class how should this be handled?
I'm assuming I need use listeners but am concerned it may be overkill for what I am trying to achieve. However I can't wrap my head around this if things get more and more intertwined- Ex: a tire now has a hubcap property that is an object and its color property is dependent on the color of the car and so on and so on.
Any help with this is appreciated and I can provide clarification if necessary but I'm hoping someone will recognize either the flaw in my construction or what approach best handles this. Thanks!
%define a car
classdef car < handle
properties
tire
door
window
paintcolorOfCar
end
%In another file Define a tire
classdef tire < handle
properties
carAttachedTo % I'm setting this property to the car object
%but think that may be a badthing
tireColor
end
methods
function colorout = get.tireColor(obj)
colorout = obj.carAttachedTo.paintcolorOfCar ;
end
采纳的回答
更多回答(1 个)
Jarrod Rivituso
2012-4-10
I think the way that I would do this is to set the actual properties to be private
properties (SetAccess=private,GetAccess=public)
paintedColorOfCar
end
and then, provide a "set" method that allows external code to modify it.
methods
function setColorOfCar(obj,inputColor)
obj.paintedColorOfCar = inputColor;
%<do any other color-change related tasks
end
end
Then, in the tire class, you could force the user to use the set method in the Car class
t = Tire;
t.carAttachedTo.setColorOfCar('blue');
Also, if your Tire class must have a color property of its own, and it is truly derived from the Car's color, then just provide a get method in the tire class that calculates it
methods
function out = getColorOfTire(obj)
out = obj.carAttachedTo.paintedColorOfCar;
end
end
The benefits of what I've outlined are that it provides one place (the Car) where the color property is stored, and the various other objects provide helpful methods to either modify or interpret that value.
You could also use listeners, but I agree with you that it might not be worth the effort.
类别
在 帮助中心 和 File Exchange 中查找有关 Engines & Motors 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!