views:

140

answers:

7

If I need two modes in my application what design pattern would I use so I can prevent ugly conditional code? App is currently MVC, but I don't want conditional code in my controllers and don't want two controllers for each view unless I have to.

Any suggestions?

+2  A: 

A different subclass for each implementation, with shared functionality either in a common superclass or using the Template Method pattern.

ChrisW
A: 

It is difficult to say for sure without more information, but I would suggest the strategy pattern. You could use the same controller and just swap out the strategy object to produce the desired change in behavior.

Here is an article you may find useful: http://www.javaworld.com/javaworld/jw-04-2002/jw-0426-designpatterns.html

Guster_Q
+1  A: 

Abstract Factory, or Proxy. Your controller would contain some kind of Factory or Proxy instance that is used to retrieve a "mode" and act on it accordingly.

Droo
A: 

Perhaps the State Pattern?

FP
A: 

take a look at JSR-168, java portlet and its reference implementation, it should be similar to what you are trying to achieve.

A: 

The appropriate place for such a decision is the controller of MVC. I would recommend you write it there first. If it really is repetitive, it may be straightforward to figure out how to clean it up: you can move the conditional logic into a base class, or depending on the language, may be able to handle it with some sort of filter. You may also be able to create some "factory" for the views, which understands the "mode" of your application. Architecturally, though, all this is in the controller.

You are right to not want it in the view. This would be pretty messy. You probably want two versions of the views, one for "view" and one for "edit".

In the end, this is what controllers are for. Good luck!

ndp
A: 

In CafeTownsend demo made with PureMVC there is a similar situation where there are two different views and two separate Mediators. You absolute don't need conditional code for that. I don't know what technology and programming language you are using, but in Flex it will be a ViewStack with the ListView and EditView as children:

Corresponding mediator is registered by demand when the view is created. You can check other implementations using previous link.

mico