Or should we call it Specification Factory? It all started when James and I were working on a story. We have a Home class that instantiates various classes based on some insane heavy if-else logic. We decided that we’ve had enough of it. James suggested that we could create a Factory and convert the if-else logic to a key of String type instead. I like the Factory idea but not quite happy with having an extra string in our code just for this purpose. Then I remembered the Specification pattern that Ted introduced to us a couple of days ago. What if we use the Specification as the key? You have a map with the Specification as the key and the class you want to instantiate as the value. Then all you need to do is to iterate over the key set of the map and get the value once you find a Specification that is satisfied. A piece of code sample is shown below.
for (Specification spec: classMap.keySet()) {
if (spec.isSatisfiedBy(someObject)) {
return classMap.get(spec);
}
}