MATLAB: Object composition and property updating

classMATLABmatlab objectsoop

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

Best Answer

You should think about whether the tire needs to be exposed as a public property on the car, or whether it can be private. In any case, one approach for your problem is to use SET methods for properties. An example is below, where the car has a public color, which when set updates the car's bodyColor and its tire's paintColor.
classdef Car < handle
properties(Dependent)
color;
end
properties(Access = private)
tire;
bodyColor;
end
methods
function set.color(this, v)
this.bodyColor = v;
this.tire.paintColor = v;
end
function v = get.color(this)
v = this.bodyColor;
end
function obj = Car
obj.tire = Tire;
obj.color = 'black';
end
end
end
classdef Tire < handle
properties
paintColor = 'black';
end
end
Using that approach, the tire doesn't even need to know what car it is attached to. Now if it is the case that you need to have the tire exist separately from the car, another approach would be to have the tire's color dependent upon the car it is attached to:
classdef Car < handle
properties(Dependent)
color;
end
properties(Access = private)
tire;
bodyColor;
end
methods
function set.color(this, v)
this.bodyColor = v;
end
function v = get.color(this)
v = this.bodyColor;
end
function obj = Car(aTire)
obj.tire = aTire;
obj.tire.car = obj;
obj.color = 'black';
end
end
end
classdef Tire < handle
properties
car;
end
properties(Dependent, SetAccess = private)
paintColor = 'black';
end
methods
function v = get.paintColor(this)
v = this.car.color;
end
end
end