Reputation: 15234
Our legacy code has a long code of if else blocks that depend on events and object type
if(event == A && objectType == O1){
.....
}
else if (event == A && objectType == O2){
....
}
else if (....)
....
....
With more and more conditions introducing, I was thinking of replacing this logic with Command pattern for each condition. But the number of classes required would be (no. of events) * (no. of object types). Is there any simpler way to refactor this code?
Upvotes: 5
Views: 787
Reputation: 8227
The pattern you may be looking for is often called double dispatching or sometimes Visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern
Create a set of classes for events and a set for object types. Create an interface
public interface VisitEvent {
public void visit(EventA eventA);
public void visit(EventB eventB);
// for each event class
}
Within the event class, you have to invoke the visit pattern on the object type class.
public class EventA {
public void visit(ObjectTypeParent otp) {
otp.visit(this);
}
}
Presuming that the object type classes inherit from a common class
public abstract class ObjectTypeParent implements VisitEvent {
public void visit(EventA eventA) {
// default code here
}
// same for each event visit from VisitEvent
}
then
public class ObjectType01 extends ObjectTypeParent {
public void visit(EventA eventA) {
// stuff you want done for this combination
}
// don't implement the ones that have common behavior
}
Upvotes: 3
Reputation: 121702
Create a class enclosing event
and objectType
, make it implement .equals()
and .hashCode()
. Create a generic class for each execution block too.
Then you'll be able to use a Map
and a simple lookup will return what is needed to execute.
Upvotes: 6