I encountered similar problem “if” statement vs OO Design – 1 but it is slightly different. Here is the problem that open the popup (different objects/popups) onValueChange of listbox
Popup1 p1; // different objects
Popup2 p2; // different objects
Popup3 p3;
...
listbox.add("p1");
listbox.add("p2");
listbox.add("p3");
...
listbox.addChangeHandler() {
if(getSelectedItem().equals("p1")){
p1 = new Popup1();
p1.show();
} else if() {...}
....
}
I don’t want to write “if” that if p1 then p1 = new Popup1(); p1.center();
How I can handle this situation? Any design-pattern?
Here is my solution but it is so costly
map() {
map.put("p1", new Popup1());
map.put("p2", new Popup2());
map.put("p3", new Popup3());
}
onValueChange() {
map.get(selectedItem).show();
}
One drawback is initialization all the popups. but it is require only when valueChange
I agree with leveraging the common base class when you can, but you can’t always add a method to the base class for every usage that might call for selecting between different subclasses.
Your “map” solution is a decent approach for cases where the selection logic is specific to a piece of code, like matching user action to an object (e.g. popup), and you can’t find a way to leverage the common base class.
You should defer the instantiation until you need it:
The anonymous classes are stateless, so if you wanted to be extra efficient, you could create the anonymous instances once and reuse them.