I have the following problem illustrated by the pseudo code below (might not make a whole lot of sense):
class Form {
boolean loggedOn = false;
String id = null;
...get/set shared methods
}
class SearchFormA extends Form{
String name = null;
String email = null;
...get/set methods
}
class SearchFormB extends Form{
String age = null;
String gender = null;
...get/set methods
}
class Search {
public Search(HttpServletRequest request){
String searchMode = (String) request.getSearchMode();
if("0".equals(searchMode)){
SearchFormA formA = new SearchFormA();
formA.setName((String)request.getParameter("name"));
formA.setId((String)request.getParameter("id"));
...populate form
request.getSession().setAttribute("formA",formA);
}
if("1".equals(searchMode)){
SearchFormB formB = new SearchFormB();
formB.setAge((String)request.getParameter("age"));
formB.setId((String)request.getParameter("id"));
...populate form
request.getSession().setAttribute("formB",formB);
}
...rest of code
}
}
What i’ve done is using reflection, but is there any other way to do it at compile time?
I’ve also tried Factory method, but the classes SearchFormA and SearchFormB does not have much in common.
EDIT: ok basically, in this case i have 4-5 searchModes, each searchMode has a different form. Between these forms they share certain similar fields. In future i might have to add 10 searchModes and it’s going to be repeating alot of populating of the same fields.
What you’re obviously trying to avoid is that in the Search method you’d have to keep appending to the if structure (spaghetti code).
I feel like the situation you’re describing isn’t all that different from the one I wrote this answer for. That would mean that Strategy and Template (and others) could come in handy here.
Cheers,
Wim