I have the following class (in JEE, can be made similarly in Spring):
@Singleton
public class MyUnknownPatternClass {
@Inject @Any Instance<SomeInterface> instances;
public SomeInterface getMatchingInstance(Object someDiscriminator) {
for(SomeInterface instance : instances) {
if(instance.supports(someDiscriminator)) {
return instance;
}
}
throw new IllegalArgumentException("Could not find a matching instace for " + someDiscriminator.toString());
}
}
Using dependency injection's discovery to locate all instances of the matching interface, this allows me to totally decouple strategies and the code using it.
For example, if I'm in a banking application, and I'm having different TransportProvider
s which implement a travel(Location l)
method, my business logic can then focus on following regular flow, for, say a travelling salesman:
Salesman m =...;
Location l = m.getStartLocation();
TransportProvider t = myUnknownPatternClass.getMatchingInstance(m.getTravelMethod());
for(Location d : m.getDestinationsToVisit())
l = t.travel(d);
m.doBusinessHere(l);
}
Thus decoupling whether the salesman travels by foot, boat, car, or any other method.
My understanding is that a factory actually instantiates objects. A servicelocator is more generic, and allows for runtime registration, and the above code seems to do neither. It is not a whiteboard pattern, as it only returns a single instance.
However, it's a very useful pattern, and it would be nice to talk about it properly.
What, then, is it?
And what would then be a proper name for the class (i.e. SomeInterfaceLocator
, or SomeInterfaceFactory
)?
Aucun commentaire:
Enregistrer un commentaire