lundi 17 avril 2017

How to replace switch with polymorphism?

I have 2 applications: application_1 and applicaion_2

appplication_1 sends messages of different types to application_2

there several types. I can declare enum of these types.

enum MessageType{
   TYPE_1,
   TYPE_2,
   ...
}

In application_2 framework I use suggest me write following API

public void handle(Object o){
    //logic
}

I think about how to build classes to process each message separately.

I understand that I can declare common type for all messages:

abstract class AbstractMessage{
    MessageType type;
    Object o;    
}

and in application_2 inside handle I can write smth like this:

MessageType mt = ((AbstractMessage) o).getType();
  switch(mt){
     case TYPE_1: 
        //handle TYPE_1
        break;
     case TYPE_2: 
     //handle TYPE_2
     break;
     ....
  }

But this code looks ugly.

Please, help to find nicer solution.

Aucun commentaire:

Enregistrer un commentaire