Avis sur une implémentation rapide de WeakIdentityMap
Bonjour à tous,
J'ai codé un truc crade à la barbare et du coup je doute à mort sur la validité de mon histoire.
Voici le postulat :
- J'ai des objets métiers (avec une classe racine métier) auxquels j'associe des propriétés GUI.
- Je ne sais pas quand ces objets vont être libérés (pas de mécanisme de notification)
- Il y aurait beaucoup de code à modifier pour mettre en place un mécanisme de notification/listener
J'ai donc codé ceci à la sauvage :
Code:
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
|
public class Identity {
final Object ref;
protected Identity(Object ref) {
this.ref = ref;
}
public int hashCode() {
return System.identityHashCode(ref);
}
public boolean equals(Object o) {
return o != null && o instance Identity && ref == ((Identity)o).ref;
}
}
public class abstract BusinessRoot implements Serializable {
private final long id;
private transient Identity identity = null;
public BusinessRoot(final long id) {
this.id = id;
}
public long getId() { return id; }
public Identity getIdentity() {
if (identity == null) {
identity = new Identity(this);
}
return identity;
}
public int hashCode() {
return id;
}
public boolean equals(Object o) {
return o != null && o instance BusinessRoot && id == ((BusinessRoot)o).id;
}
}
// Exemple
public class Main {
public static void main(String[] args) {
Map<Identity, Map<String, Object>> propertyMap = new WeakHashMap<Identity, Map<String, String>>();
BusinessRoot object1 = new BusinessRoot(0) {};
BusinessRoot object2 = new BusinessRoot(0) {};
propertyMap.put(object1.getIdentity(), new HashMap<String, String>());
propertyMap.put(object2.getIdentity(), new HashMap<String, String>());
// ...
object1 = null;
// ...
}
} |
- Voyez-vous un problème la dedans ?
- Connaissez-vous une implémentation existante de WeakIdentityHashMap (Je suis limité dans les librairies que je peux utiliser et je peux pas copier de source) ?
- Une meilleure façon de faire ?