Class selection dynamically at runtime

Im trying to find a solution in which the class that processes the "message" is selected at runtime depending on the type of message. I know I can use something like this

if msg_type = "A" MsgAProcessor.execute(message); else if msg_type = "B" MsgBProcessoror = execute(message); .... .... .... 

I do not want to use the above approach, because I do not want the code to know anything about the types of messages that I could handle. I want to be able to add a new message processor in the future for a new message type. The solution I'm thinking of now is as follows

There are currently 3 message processors

 MsgAProcessor MsgBProcessor MsgBProcessor 

All three classes have a method called execute that will process the message in their own way. I created the MsgProcessor interface and added the execute () method in the interface.

Now it’s hard for me to understand which message processor should call the caller without checking the type of message. For example, I can’t do it

MsgProcessor proc = new MsgAprocessor () proc.execute ()

The above should be indicated in the if statement, since it must be called immediately after determining the type of message. I would also like to avoid instantiating using an implementation class type.

Is there a better way to achieve the same?

I want to be able to just call MsgProcessor.execute from the interface and have a runtime that knows the implementation class to call based on the message type.

0
java java-ee class-design classloader
source share
3 answers
  • It has an interface Processor that has a execute () method. All your three MsgProcessors implement this.
  • Have a separate ProcessorControl class that has a submit (String message) method. Whenever a new message arrives, you simply execute ProcessorControl.submit (message)
  • ProcessorControl now has an addProcessor (Proccesor proc, String type) method that adds processors to the hash table with the type as the key. Therefore, each processor is now assigned with a type.
  • In the submit method, just get hashtable.get (type) .execute (proc)

This is a simple team template.

+5
source share

You can use a map to display from a message type to a message processor. To decouple implementations, you can use ServiceLoader: http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html

+1
source share

Soon you want to use dynamic class loading: Class.forName(THE CLASS NAME)

Your command can either contain the full name of the class or map to it using a properties file or naming convention. All implementations of your team must implement the interface (as you already did). When you get the command to get the class name from it, then create an instance of the command and call its execution method:

((Processor)Class.forName(className).newInstance()).execute()

+1
source share

All Articles