1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public abstract class JComponentSettingHelper<T extends JComponent> {
private final static Map<Class<?>, JComponentSettingHelper<?>> INTERNAL_MAP = new HashMap<Class<?>, JComponentSettingHelper<?>>();
//on enregistre les implmentations
static {
register(JTextField.class, new JTextFieldSettingHelper());
// ect...
}
private JComponentSettingHelper() {
}
// enregistrement d'une implementation
private static <A extends JComponent> void register(Class<A> key,
JComponentSettingHelper<A> value) {
INTERNAL_MAP.put(key, value);
}
// methode à appeler
public static <A extends JComponent> A getProperlySetComponent(A a,
Object value) {
// on cherche si l'implementation specifique pour la classe existe
if (INTERNAL_MAP.containsKey(a.getClass())) {
return ((JComponentSettingHelper<A>) INTERNAL_MAP.get(a.getClass()))
.getInternalProperlySetComponent(a, value);
}
// sinon on cherche si une on a une implmenation d'une superclasse de
// l'objet sous la main
else {
for (Class<?> key : INTERNAL_MAP.keySet()) {
if (key.isAssignableFrom(a.getClass())) {
return ((JComponentSettingHelper<A>) INTERNAL_MAP.get(key))
.getInternalProperlySetComponent(a, value);
}
}
// si y en a pas, on balance une exception
throw new UnsupportedOperationException(
"Operation not supported for component: "
+ a.getClass().getName());
}
}
// methode à surcharger selon composant
abstract T getInternalProperlySetComponent(T t, Object value);
// Une implementation
private static class JTextFieldSettingHelper extends
JComponentSettingHelper<JTextField> {
@Override
public JTextField getInternalProperlySetComponent(JTextField t,
Object value) {
t.setText(value.toString());
return t;
}
}
// etc...
} |
Partager