mardi 21 juin 2016

How to delegate to services by class type?

I have different class types, and depending on some conditions, I want to delegate to the appropriate service that can handle those class types.

Example: I have several classes as follows.

class Student;
class Prof;
...

For each class there is a service, implementing:

interface IPersonService {
    void run();
}

And I have a mode that is found by some conditions:

enum PersonType {
    STUDENT, PROF;
}

When I delegate:

@Autowired
private StudentService studentService;

@Autowired
private ProfService profService;

//@param mode assume known
public void delegate(PersonType mode) {

    //assume there are several of those switch statements in my business code
    switch (mode) {
        case STUDENT: studentService.run(); break;
        case PROF: profService.run(); break;
        default: break;
    }
}

Problem: When introducing additional classes, I have to both modify the PersonType and add an additional enum (which is no problem), but I also have to extend any switch statement and add calls to additional delegation services. Also I have to explicit autowire those services to the switch delegator.

Question: how could I optimize this code, to just implementing new Services for any additional class, and not having to touch any of the switch statements?

Aucun commentaire:

Enregistrer un commentaire