Search code examples
javamodel-view-controllerinterfaceobserver-pattern

Interface between a 'model' and 'view'


A program has a view and a model (using the term loosely) in which the view is observing the model. The model has a handful of states, and the view has a handful of jpanels that are mapped onto the states (some states have several corresponding jpanels apiece). Using a cardlayout, one jpanel displays at a time, and a state change or change within a state will swap out the current jpanel for another. The program works, but it seems like bad practice for the view and model to assume that there are exactly 5 states and 7 views. How may this be implemented.


class Model implements Observable {
  State A, B, C;
  final int VIEW_A = 0, VIEW_B = 1, VIEW_C0 = 2, VIEW_C1 = 3; 
  int stateView;

//argument will be one of the final ints above void setStateView(int stateView) { this.stateView = stateView; notifyObservers(); }

void getStateView() { return stateView; } }

class View implements Observer { void update(Observable o) { //will use one of the ints above to identify the correct jPanel to display setJPanel ( o.getStateView() ); } }

I recognize the code above is an awful way of going about this. That's why I'm here. Help?


Solution

  • A few things:

    1. In using your model to maintain state, you are using the MVC design pattern correctly.

    2. Assuming there are only 5 states is certainly ok if there are only 5 states. I do disagree with another practice you are using. Instead of using a bunch of final int declarations, I would define a enum that represents your state. I think that this could be a major reason why you think your program is ugly. It is, in my opinion, and your decision to not use enum is the reason.

    3. This design is not very extensible. What if you eventually need 147 states? This is something to think about. One option is to use something besides a single integer as your state descriptor. Since I don't know what you're designing, it's hard for me to give good suggestions on this point.

    Edit: to address another answer posted suggesting use of the Mediator pattern: I think this is overkill for this simple of an application. Your model is straightfoward, and your maintenance of states is not overly complex. Design is important, but going overkill on your design can lead to pitfalls as well.

    Good luck,

    -tjw