whats the name of this pattern?
- by Wes
I see this a lot in frameworks.
You have a master class which other classes register with.
The master class then decides which of the registered classes to delegate the request to. An example based passed in class may be something this.
public interface Processor {
public boolean canHandle(Object objectToHandle);
public void handle(Object objectToHandle);
}
public class EvenNumberProcessor extends Processor {
public boolean canHandle(Object objectToHandle) {
if (!isNumeric(objectToHandle)){
return false
}
return isEven(objectToHandle);
}
public void handle(objectToHandle) {
//Optionally call canHandleAgain to ensure the calling class is fufilling its contract
doSomething();
}
}
public class OddNumberProcessor extends Processor {
public boolean canHandle(Object objectToHandle) {
if (!isNumeric(objectToHandle)){
return false
}
return isOdd(objectToHandle);
}
public void handle(objectToHandle) {
//Optionally call canHandleAgain to ensure the calling class is fufilling its contract
doSomething();
}
}
//Can optionally implement processor interface
public class processorDelegator {
private List processors;
public void addProcessor(Processor processor) {
processors.add(processor);
}
public void process(Object objectToProcess) {
//Lookup relevant processor either by keeping a list of what they can process
//Or query each one to see if it can process the object.
chosenProcessor=chooseProcessor(objectToProcess);
chosenProcessor.handle(objectToProcess);
}
}
Note there are a few variations I see on this. In one variation the sub classes provide a list of things they can process which the ProcessorDelegator understands. The other variation which is listed above in fake code is where each is queried in turn.
This is similar to chain of command but I don't think its the same as chain of command means that the processor needs to pass to other processors.
The other variation is where the ProcessorDelegator itself implements the interface which means you can get trees of ProcessorDelegators which specialise further. In the above example you could have a numeric processor delegator which delegates to an even/odd processor and a string processordelegator which delegates to different strings.
My question is does this pattern have a name.