Designing for a limited list


General J2EE: Designing for a limited list

  1. Designing for a limited list (1 messages)

    I believe there is a pattern for this ... this should be a very common issue:
    I have an object who contains an attribute with say 3 possible values, I have to do something very dramatically different in 3 cases (while loop through a bunch of instances). Now even if I have the possible attribute values stored in a lookup table I still can't avoid the following codes:
    for (Iterator it = list.iterator(); it.hasNext();) {
      String attr = myObject.getMyAttr();
      if (attr.equals("CASE_A"))
      els if (attr.equals("CASE_B"))
      els if (attr.equals("CASE_C"))

    Let's say you just can not possiblly generalize doSomethingVeryX part, how do you get rid of the "if"s? Or is that asking (trying to archtect) too much....
  2. Designing for a limited list[ Go to top ]

    here we go:

    public interface ObjectProcessor {
       public void processObject(Object obj);

    public class CaseAProcessor implements ObbjectProcessor....

    public class CaseBProcessor implements ObbjectProcessor....

    public class CaseCProcessor implements ObbjectProcessor....

    Map processors = new HashMap();
    proecssors.add("case A", new CaseAPRocessor());
    proecssors.add("case B", new CaseBPRocessor());
    proecssors.add("case C", new CaseCPRocessor());

    for (Iterator it = list.iterator(); it.hasNExt();) {
       ObjectProcessor proessor = processors.get(CASE);

    this code wouldn't actually compile as is, but I think you'll get the idea. the map should be initialized somewhere in a static structure, at application startup.

    hope it helps.

    emil ( ) .