aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes MVC -2+ views for 1 controller?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "MVC -2+ views for 1 controller??" Watch "MVC -2+ views for 1 controller??" New topic
Author

MVC -2+ views for 1 controller??

Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
Hi,
I have a bit of a problem. I'm using the MVC architecture for my swing app.
I split my user interface class in 2 separate classes because it was getting big. I created a controller for each view because I read that a view should only have one controller and vice-versa. My problem is, when the user changes values in the first view, fields from the second view must be disabled.
How can I get the 2 controllers to talk to each other? Should I instead use only 1 controller for both views?
Thanks,
Marie
Bill Dudney
Author
Ranch Hand

Joined: Sep 05, 2003
Posts: 234
Hi Marie,
Does your model post events? The 'typical' way to handle this sort of thing is to have your model post events and your controllers to listen. If somthing in interest changes the the controller can tell the view to update.
The GoF book has a great discussion of this pattern refered to as Observer in their book.
Hope this helps.


TTFN,<br /> <br />-bd-<br /> <br /><a href="http://www.amazon.com/exec/obidos/ASIN/0471449156/qid=1064343733/sr=2-1/ref=sr_2_1/002-8375300-3666449" target="_blank" rel="nofollow">Jakarta Pitfalls</a> | <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0471146153/qid=1064343733/sr=1-2/ref=sr_1_2/002-8375300-3666449?v=glance&s=books" target="_blank" rel="nofollow">J2EE AntiPatterns</a> | <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0471462071/qid=1064343733/sr=1-3/ref=sr_1_3/002-8375300-3666449?v=glance&s=books" target="_blank" rel="nofollow">Mastering JavaServer Faces</a> | <a href="http://bill.dudney.net/roller/page/bill" target="_blank" rel="nofollow">Blog</a> | <a href="http://www.jroller.com/page/BillDudney" target="_blank" rel="nofollow">Eclipse Blog</a> | <a href="http://www.sourcebeat.com/TitleAction.do?id=2" target="_blank" rel="nofollow">Eclipse 3 Live</a>
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
I read that a view should only have one controller and vice-versa
I'd be interested to find out where you read this, because it seems fundamentally at odds with what I though MVC is all about. MVC (as I have used it) is an architectural pattern specifically designed to support multiple views on the same data.
For a real code examples, demonstrating what I mean, see this older thread.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Frank, just a quick look at the first example in that other thread looks like the controller is pushing change events to the view.

That's one flavor. Another is:

Now the model publishes an event that the views all listen for. The event may contain the data that changed, or just announce that something changed so the view can fetch the data afresh. This could have had two controllers, too.
You have to worry about dependencies here. Assume the model is stable and we add and remove views all the time, so the model should own the interface that all views must implement to receive events.
I show some other pub sub variations on my Messaging Patterns page. That page is mostly - but not necessarily - about asynchronous MOM messaging, but the picture with the intermediary could work here, too.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
The book I'm using ("Teach yourself Object Oriented programming in 21 days") says that a model may have many views, and a view may have many models, but the relationship between the controller and the view should be 1-1. I don't have the book with me now, but I will double-check what it says...maybe I misunderstood.
I also have the book "Agile Software Development" by Robert Martin. I only read the first few chapters, but I think I saw something about the Observer pattern in there.
Thanks for all your replies. I'll come back if I have more questions.
Marie
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Is it possible that the scenario is like this?
a) MVC applied to GUI-widgets building has a one to one View Controller relationship. Specially because in the current GUI frameworks they seem to have been coalesced into one object, called IU delegate (ComponentUI class) in Java.
b) MVC as an arquitectural pattern. A sole controller is allowed to interact with all the views. Though, more than one might also be needed!


SCJP2. Please Indent your code using UBB Code
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Hmmm, I've always allowed controllers to manage multiple WINDOWS. Whether that is multiple VIEWS or not may be up to you. The controller is where I'd put tricky stuff about opening subwindows, sequencing UI flow, etc.
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
Originally posted by Frank Carver:
I read that a view should only have one controller and vice-versa
I'd be interested to find out where you read this, because it seems fundamentally at odds with what I though MVC is all about. MVC (as I have used it) is an architectural pattern specifically designed to support multiple views on the same data.
For a real code examples, demonstrating what I mean, see this older thread.

Thanks for the information about the older thread, Frank. That's exactly what I was looking for.
Marie
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Marie Mazerolle:
The book I'm using ("Teach yourself Object Oriented programming in 21 days") says that a model may have many views, and a view may have many models, but the relationship between the controller and the view should be 1-1.

Does the book also say *why*?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
Originally posted by Ilja Preuss:

Does the book also say *why*?

Unfortunately, no. In the chapter about OO and User Interface Programming, it says: "The view and controller are also closely related to one another. a controller is almost always used exclusively with a specific view. You can try to find reuse through careful design; but even if you don't, the MVC pattern still provides a good division of responsibility between the objects. OO is not simply a means for reuse."
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Originally posted by Marie Mazerolle:

Unfortunately, no. In the chapter about OO and User Interface Programming, it says: "The view and controller are also closely related to one another. a controller is almost always used exclusively with a specific view. You can try to find reuse through careful design; but even if you don't, the MVC pattern still provides a good division of responsibility between the objects. OO is not simply a means for reuse."

which breaks the very principle of having them in the first place.
If they're so closely coupled why not simply combine them and save a few object creations and method calls?


42
HS Thomas
Ranch Hand

Joined: May 15, 2002
Posts: 3404
If they're so closely coupled why not simply combine them and save a few object creations and method calls?

Do you mean combine the Controller and View or the Model and View ?
The controller may be redundant in the latter case.
I found this thread useful
http://www.coderanch.com/t/136453/sr/certification/passed
regards
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
I also recall that there was also some interesting discussion of MVC in this other old thread.
You get to see more of Stan's lovely diagrams, too
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The tool for those lovely charts (thanks!) is linked at the bottom of this page: http://www.surfscranton.com/architecture/JavaPages.htm It's in REXX, free interpreter from http://www.lightlink.com/hessling/ If anybody does a Java or Perl version, lemme know!
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
Thanks for all the replies. I read all the recommended threads. Debra Bellmaine's thread in the SCJD forum was really helpful.
From the diagram she drew in this thread and the description she gave, it seems that :
a view may have many models,
a model may have many views,
a controller may have many views,
but a controller may only have one model.

Is that correct? Or is just one way to do build the app?

Thanks,
Marie
[ September 30, 2003: Message edited by: Marie Mazerolle ]
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
I *think* I'm starting to understand. A controller may have many views, but each view will only have one controller instance, correct?
I initially thought that several views could share the same controller instance, but from what I've read and from looking again at my code, it doesn't seem possible because the controller instance is not passed to the view's constructor, it is instantiated in the view's constructor.
The reason I thought a controller instance could be shared between several views is because initially, my view was in one big class, but then I realized I could split it, thus making the code easier to maintain, and providing an opportunity to reuse some of my gui components. So I thought, they were using the same controller instance before, so they should be doing the same thing now!
Am I going in the right direction?
I hope that this discussion will help newbies like me understand MVC. It is simple for simple applications, but it can get a lot more complicated...
Thanks,
Marie
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I initially thought that several views could share the same controller instance, but from what I've read and from looking again at my code, it doesn't seem possible because the controller instance is not passed to the view's constructor, it is instantiated in the view's constructor.

That certainly works, but it's not the only way, of course. I did a little app where the main() method did nothing but create the model, view and controller, give them the appropriate pointers to each other, and call controller.start(). The MVC classes all have compile-time dependencies on interfaces and not concrete classes.
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
Originally posted by Stan James:

That certainly works, but it's not the only way, of course. I did a little app where the main() method did nothing but create the model, view and controller, give them the appropriate pointers to each other, and call controller.start(). The MVC classes all have compile-time dependencies on interfaces and not concrete classes.

That sounds more like what I want to do. Thanks for the tip!
Marie
HS Thomas
Ranch Hand

Joined: May 15, 2002
Posts: 3404
The diagram you posted is the one Sun published a while ago.
I think that fits with GoF MVC.
I've come across references to Struts MVC and at some point they will integrate Java Server Faces with Struts.
There are other approaches to MVC as described in this wiki page:
Model View Controller As An Aggregate Design Pattern
So I think it all depends on the context as to which MVC you use.
What you've posted is certainly a good starting point.
regards
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
I've learned a lot about MVC in the past weeks, but I still haven't been able to solve my problem.
I will describe my app, and hopefully someone will be able to help me. So here it goes:
We have a directory of companies that we want to manage. The user interface is so far composed of:
Panel 1: displays company details (name, phone number, contact info, etc)
Panel 2: displays industry sectors (manufacture, agriculture, etc)
Panel 3: displays buttons to insert, save, delete and cancel
Panel 4: displays a jcombobox of all companies and buttons to browse (next, previous, first and last)
My panels were originally all in the same view class, using the same model and controller. But I decided to split them up for later reuse.
The first problem that showed up is that if the user views a company, and changes company details (on Panel 1), the navigational controls on Panel 4 and the insert button on Panel 3 should be disabled.
Now since I first posted here, I've been examining a lot of solutions proposed by JR members, but it seems that every time I think something will work, I always hit a wall.
I was thinking that my views could all share the same controller because they're all related. But if the user changes the company name, I must disable the navigational buttons. How do I do that? I imagine that in my controller, I would have something like view.disableNavigationButtons, and in my class with the navigational buttons (Panel 4) , I would write the code to disable my combobox and the next, previous, first and last buttons.
But in my controller class, my views are (or will be) stored in an ArrayList. When I call view.disableNavigationButtons, how do I know which view to use? Do I have to check the object type before I make the call? I imagine not because it would then violate the Open-Closed Principle described in "Agile Software Development" by Robert Martin.
I've been turning this in my head for 2 weeks now, and I still haven't found a solution. Having a background in web development only (ASP & PHP), I find developping an application using MVC extremely challenging... but never boring.
Which brings another question that maybe I should ask in another thread: How did you learn OOAD & OOP (and design patterns)? If you're self-taught (and even if you're not), then you have my respect because the more I study, the more I find it's a complex subject.
Thanks,
Marie
Marie Mazerolle
Ranch Hand

Joined: Oct 01, 2002
Posts: 81
It just occurred to me. Maybe I'm going about this totally the wrong way because I misunderstood the MVC architecture.
What if I just use my 4 classes (panels 1- 4 in post above), and declare one view (let's say it's a frame) that would assemble my panels.
So my gui code would be split up, but I would have one view, one controller and one model.
I guess there's only one way to know, and that is to try!
Marie
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
I feel that one point of misunderstanding might be that you seem to want to communicate direct from view-to-view (or maybe view-controller-view). In a real MVC system, all communication between views is done via the model.
Consider the following (with panel == view):
  • user changes a company name on panel 1.
  • panel 1 notes that the field has changed
  • user clicks "save" button on panel 3
  • panel 3 tells its controller (controller.saveChanges() or whatever)
  • controller fetches any changed data from all panels and updates model
  • model sends a data-updated message to all the subscribed views
  • panel 1 is subscribed but doesn't care
  • panel 2 is subscribed but doesn't care
  • panel 3 is not subscribed as it is effectively static
  • panel 4 is subscribed and acts on the data-updated message to update its display to match


  • At no point does any views need to know about any other. Nor does the model need to know anything about the views, what order they are stored in, or even any methods they provide other than the ability to receive a message.
    Is that any clearer? Do you think this approach might work in your situation?
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Marie Mazerolle:
    But in my controller class, my views are (or will be) stored in an ArrayList. When I call view.disableNavigationButtons, how do I know which view to use? Do I have to check the object type before I make the call? I imagine not because it would then violate the Open-Closed Principle described in "Agile Software Development" by Robert Martin.

    Why don't you just call disableNavigationButtons on *every* view? Those without buttons would simply do nothing...

    Which brings another question that maybe I should ask in another thread: How did you learn OOAD & OOP (and design patterns)? If you're self-taught (and even if you're not), then you have my respect because the more I study, the more I find it's a complex subject.

    I am self-tought - and yes, it's a complex subject. It took me years to grok, and I am still learning. The biggest effect had reading Fowlers "Refactoring" for me. Well, the biggest besides much trial and error, of course...
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Frank Carver:
  • user changes a company name on panel 1.
  • panel 1 notes that the field has changed
  • user clicks "save" button on panel 3
  • panel 3 tells its controller (controller.saveChanges() or whatever)
  • controller fetches any changed data from all panels and updates model

  • [/QB]

    That's not MVC as I understand it. In MVC, the View doesn't react to user input - that's the Controllers responsibility. When you type something into a JTextField, the part reacting to your key strokes "is a Controller". The "View part" only gets notified by the Controller and displays the entered data.
    Frank Carver
    Sheriff

    Joined: Jan 07, 1999
    Posts: 6920
    Ilja wrote: That's not MVC as I understand it. In MVC, the View doesn't react to user input - that's the Controllers responsibility.
    Oh, there's a whole 'nother argument there.
    In the case where the technology implementing the view is completely "dumb" (a text screen, for example), I agree with you. The view code generates the text, the keyboard sends characters direct to the controller.
    In a modern GUI, however, this distinction is not at all clear. When I move my mouse and click the button, my application typically does not see "raw input" in terms of absolute mouse movement and clicking, but instead, some sort of complex relative event, dependent on how the application has chosen to display its text, graphic images, buttons and so on. The application sees "single click on button 0xffeeddca".
    Taking it a little further, consider the kind of graphic-based interface which lets me "drag" points on a graph, or adjust on-screen knobs and sliders. The active behaviour of these combined input/output operations depends almost entirely on how the view has been configured. Resize a window and the knobs and sliders might resize or move, but that should have no effect on the underlying model, or indeed the controller.
    In these cases my approach is to consider the localized activity of the GUI (the kind of stuff which is handled for you by a client API, or a web browser, for example) as part of the view.
    The controller component serves to mediate the communication between view and model (and vice versa), and to isolate each from knowledge of the other. It is the controller which encapsulates the knowledge of how to read an updated field (or the new location of a dragged graph point etc.) from the view, and also how to package or convert that information and apply it to the model. It is the controller which contains the code for creating and destroying views, subscribing/unsubscribing them to event/data feeds from a model and so on.
    Although there may be a MVC-like architecture happening within the UI API, or within the web browser, the important thing is that our application doesn't care. The MVC that our code implements can be at a courser-grained level. Our "view" canbe thought of as the "model" of the API layer.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Frank Carver:
    Although there may be a MVC-like architecture happening within the UI API, or within the web browser, the important thing is that our application doesn't care. The MVC that our code implements can be at a courser-grained level. Our "view" canbe thought of as the "model" of the API layer.

    Yes, I totally agree that this is what typically is done and that it's a reasonable approach.
    My point still stands - that's not "pure MVC", but more along the lines of Model View Presenter.
    In MVC, you have the Controller handling input and notifying view and model; the view only reacts to events from both controller and model.
    In MVP, you have the view being a thin presentation layer tightly bound to (and abstracting from) the proprietary presentation API (e.g. Swing) and the presenter containing all the presentation and input handling logic, glueing view and model together.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Just found this very good explanation on MVC: http://ootips.org/mvc-pattern.html
    Marie Mazerolle
    Ranch Hand

    Joined: Oct 01, 2002
    Posts: 81
    Originally posted by Ilja Preuss:

    Why don't you just call disableNavigationButtons on *every* view? Those without buttons would simply do nothing...

    I did think of that, Ilja, but I didn't think it would be an acceptable approach to have methods that don't do anything just so my code wouln't break.
    But I'm the uneducated one here, so is that how you would do it?
    Thanks,
    Marie
    Marie Mazerolle
    Ranch Hand

    Joined: Oct 01, 2002
    Posts: 81
    Originally posted by Frank Carver:
    [QB]I feel that one point of misunderstanding might be that you seem to want to communicate direct from view-to-view (or maybe view-controller-view).
    [QB]

    You're right, I am trying to communication from view-controller-view. It seems the only way since my controller listens for user actions on my view.
    Here's what my code looks like:


    In a real MVC system, all communication between views is done via the model.

    I don't understand how I should change my code to fit that description.
    Thanks,
    Marie
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Marie Mazerolle:
    I don't understand how I should change my code to fit that description.

    That depends on *why* you want to disable the buttons. Why do you?
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Marie Mazerolle:

    Is that correct? Or is just one way to do build the app?

    Well, actually *both*. MVC *is* just *one* way to build an app.
    Remember that *every* pattern is *not* good in itself - you always need to consider the context it is used in.
    MVC is valuable when you need to change the way information is put into the system, how that data is processed and how the result is presented to the user independently of each other. If you won't need to do that, it might just add unnecessary complexety.
    Alternatice approaches are Model View Presenter, Document View etc. and even combinations.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Marie Mazerolle:

    I did think of that, Ilja, but I didn't think it would be an acceptable approach to have methods that don't do anything just so my code wouln't break.
    But I'm the uneducated one here, so is that how you would do it?

    I seriously don't know - it's probably something I would consider.
    Pro: the controller doesn't need to know where the buttons reside, so this is easy to change.
    Con: if you do this very often, it leads to big, cluttered class interface.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Frank Carver:
    In a real MVC system, all communication between views is done via the model.

    I don't think this is fully true. For example, if there is a button which just lets me navigate to a different view, in my opinion the model shouldn't even be aware of this.
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    BTW, thanks for this great thread! For years I had problems fully understanding this pattern - discussing it here has helped me very much reconciling my thoughts!
    Marie Mazerolle
    Ranch Hand

    Joined: Oct 01, 2002
    Posts: 81
    Originally posted by Ilja Preuss:

    That depends on *why* you want to disable the buttons. Why do you?

    I just want to make sure that if the user changes, let's say, a company phone number, he/she must save before looking at another company's information.
    Marie Mazerolle
    Ranch Hand

    Joined: Oct 01, 2002
    Posts: 81
    Originally posted by Ilja Preuss:

    Remember that *every* pattern is *not* good in itself - you always need to consider the context it is used in.
    MVC is valuable when you need to change the way information is put into the system, how that data is processed and how the result is presented to the user independently of each other. If you won't need to do that, it might just add unnecessary complexety.
    Alternatice approaches are Model View Presenter, Document View etc. and even combinations.

    Good point, Ilja. I *think* MVC is appropriate, because I know the requirements will change a lot in the next few months, not from a functionality point of view, but more the gui. That's why I would like to be able to extend, and not modify my application and I think that MVC will permit this.
    Besides, this is also a project that I can use to learn design patterns. Even if MVC is not the most appropriate, it's okay because the application is not very big, so I could just re-write the whole thing if needed be.
    So I will try to apply MVC as best I as can, and then I'll go from there. But thanks for all your suggestions. They're all very much appreciated!
    Marie
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Marie Mazerolle:

    I just want to make sure that if the user changes, let's say, a company phone number, he/she must save before looking at another company's information.

    So the appropriate part of the model could have a property "was modified after last save" and could notify the view if that property changes state?
    Marie Mazerolle
    Ranch Hand

    Joined: Oct 01, 2002
    Posts: 81
    Originally posted by Ilja Preuss:

    So the appropriate part of the model could have a property "was modified after last save" and could notify the view if that property changes state?

    yeeeess...
    I will try that and see if it works. Thanks so much!
    Marie
     
     
    subject: MVC -2+ views for 1 controller??