Featured post
java - “if” statement vs OO Design - 2 -
i encountered similar problem “if” statement vs oo design - 1 different. here problem open 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 write "if" if p1 p1 = new popup1(); p1.center();
how can handle situation? design-pattern?
here solution costly
map() { map.put("p1", new popup1()); map.put("p2", new popup2()); map.put("p3", new popup3()); } onvaluechange() { map.get(selecteditem).show(); }
one drawback initialization popups. require when valuechange
i agree leveraging common base class when can, can't add method base class every usage might call selecting between different subclasses.
your "map" solution decent approach cases selection logic specific piece of code, matching user action object (e.g. popup), , can't find way leverage common base class.
one drawback initialization popups. require when valuechange
you should defer instantiation until need it:
interface showable { void show(); } map() { map.put("p1", new showable() { void show() { new popup1().show(); } } ); map.put("p2", new showable() { void show() { new popup2().show(); } } ); map.put("p3", new showable() { void show() { new popup3().show(); } } ); } onvaluechange() { map.get(selecteditem).show(); }
the anonymous classes stateless, if wanted efficient, create anonymous instances once , reuse them.
- Get link
- X
- Other Apps
Comments
Post a Comment