1 16 package org.apache.commons.collections.functors; 17 18 import java.io.Serializable ; 19 import java.util.Iterator ; 20 import java.util.Map ; 21 22 import org.apache.commons.collections.Closure; 23 import org.apache.commons.collections.Predicate; 24 25 34 public class SwitchClosure implements Closure, Serializable { 35 36 37 static final long serialVersionUID = 3518477308466486130L; 38 39 40 private final Predicate[] iPredicates; 41 42 private final Closure[] iClosures; 43 44 private final Closure iDefault; 45 46 56 public static Closure getInstance(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { 57 FunctorUtils.validate(predicates); 58 FunctorUtils.validate(closures); 59 if (predicates.length != closures.length) { 60 throw new IllegalArgumentException ("The predicate and closure arrays must be the same size"); 61 } 62 if (predicates.length == 0) { 63 return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); 64 } 65 predicates = FunctorUtils.copy(predicates); 66 closures = FunctorUtils.copy(closures); 67 return new SwitchClosure(predicates, closures, defaultClosure); 68 } 69 70 87 public static Closure getInstance(Map predicatesAndClosures) { 88 Closure[] closures = null; 89 Predicate[] preds = null; 90 if (predicatesAndClosures == null) { 91 throw new IllegalArgumentException ("The predicate and closure map must not be null"); 92 } 93 if (predicatesAndClosures.size() == 0) { 94 return NOPClosure.INSTANCE; 95 } 96 Closure defaultClosure = (Closure) predicatesAndClosures.remove(null); 98 int size = predicatesAndClosures.size(); 99 if (size == 0) { 100 return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); 101 } 102 closures = new Closure[size]; 103 preds = new Predicate[size]; 104 int i = 0; 105 for (Iterator it = predicatesAndClosures.entrySet().iterator(); it.hasNext();) { 106 Map.Entry entry = (Map.Entry ) it.next(); 107 preds[i] = (Predicate) entry.getKey(); 108 closures[i] = (Closure) entry.getValue(); 109 i++; 110 } 111 return new SwitchClosure(preds, closures, defaultClosure); 112 } 113 114 122 public SwitchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { 123 super(); 124 iPredicates = predicates; 125 iClosures = closures; 126 iDefault = (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); 127 } 128 129 134 public void execute(Object input) { 135 for (int i = 0; i < iPredicates.length; i++) { 136 if (iPredicates[i].evaluate(input) == true) { 137 iClosures[i].execute(input); 138 return; 139 } 140 } 141 iDefault.execute(input); 142 } 143 144 150 public Predicate[] getPredicates() { 151 return iPredicates; 152 } 153 154 160 public Closure[] getClosures() { 161 return iClosures; 162 } 163 164 170 public Closure getDefaultClosure() { 171 return iDefault; 172 } 173 174 } 175 | Popular Tags |