Team template with too many classes

Our old code has long if else code for blocks that depend on events and the type of object

if(event == A && objectType == O1){ ..... } else if (event == A && objectType == O2){ .... } else if (....) .... .... 

With the advent of an increasing number of conditions, I was thinking of replacing this logic with a command template for each condition. But the number of classes required would be (number of events) * (number of types of objects). Is there an easier way to reorganize this code?

+4
source share
2 answers

Create a class containing event and objectType , make it implement .equals() and .hashCode() . Create a common class for each execution unit.

Then you can use Map , and a simple search will return what needs to be done.

+5
source

The pattern you might be looking for is often called a double control room or sometimes a visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern

Create a set of classes for events and a set for types of objects. Create interface

 public interface VisitEvent { public void visit(EventA eventA); public void visit(EventB eventB); // for each event class } 

In an event class, you must invoke a template to visit the class of the object class.

 public class EventA { public void visit(ObjectTypeParent otp) { otp.visit(this); } } 

Assuming object type classes are inherited 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 } 
+1
source

Source: https://habr.com/ru/post/1486222/


All Articles