(I'm writing a large MATLAB GUI that makes significant use of MVC, so my example is written in MATLAB. However, I believe this question is language-agnostic. Please correct me if I'm wrong.)
I have a class
Model which is obviously the model for my MVC application. Suppose I have the following:
classdef Model < handle properties objectA objectB objectC end end
objectC are all objects that can be observed:
classdef objectA < handle events ObjectAEvent end methods function raise(this) this.notify('ObjectAEvent', someEventData); end end end
Now say I want my
View to respond to changes to my
Model. In particular I want the
View to respond to the
ObjectAEvent event. There are two ways to do this:
Viewdirectly subscribe to the
ObjectAEventevent. We've now coupled the
Viewinto the internals of the
Model, which I believe violates the Law of Demeter. I'm pretty sure this also violates the concept of MVC by definition.
Model"forward" the event to the
View, as follows.
classdef Model < handle properties objectA objectB objectC listeners end events eventFromObjectA ... end methods function this = Model this.listeners(1) = addlistener(this.objectA, 'ObjectAEvent', @(src, eventdata) this.notify('eventFromObjectA', eventdata); ... end end end
Viewdirectly observes the
Model, but the
Modelhas to pass the events and associated data to the
View. I suppose this is kind of the point of MVC, but now there's a coupling between each
Modeldirectly. I suppose the
Modelought to know about his
object_s, but this still feels... clunky.
Which approach is more correct? Are there other alternatives which are cleaner than either of these?
(Answers may have examples in any OOP language; I'm just most familiar with MATLAB.)