Giannis
Giannis

Reputation: 5526

How to replace if-else block using polymorphism

I am making a network application. Here is the problem:

I have a Messenger class. The Messenger has several module classes named ModuleA,B,C etc. The messenger sends MessagePacks (to other Messengers). Each MessagePack has a module destination meaning once it reaches Messenger it is forwarded to the correct Module(A,B,C etc).

At the moment in order to forward to the correct module I'm using an if-else checking for a tag on MessagePack to decide where to forward.

What I would like to do is have MessagePack subclasses instead of using tags(tags are Strings).So TypeAMessage goes to ModuleA etc. The only way I can think to do that is having an instance of Messenger in the MessagePack and call a method like this: Messenger.fowardToModuleA(this); but it doesn't make sense(and probably causes problems) to have an instance of Messenger on MessagePack.

Can anyone think of a way to complete the task I want without using the if-else checking for tag strings and preferably using MessagePack subclasses?

Upvotes: 1

Views: 571

Answers (1)

Robin
Robin

Reputation: 36601

An(other) option would be to let the Modules decide which MessagePack they accept and which not. So your Messenger would still contain/link to several Module classes, but just forward every incoming MessagePack towards all Modules like

for ( Module module : modules ){
  if ( module.canHandle( messagePack ) ){
     module.handle( messagePack );
     //if messagePacks should only be handled by one module, break
  }
}

Whether or not those module's use a String identifier on the messagepack, or only accept certain specific implementations of a messagepack interface is up to you. With this approach you have

  • a Messenger class which needs no adjustments when you add modules or messagepack types
  • one entry-point for all messages on a messenger
  • a module should only contain logic/knowledge for the type of messagepacks it can handle. So when adding a new messagepack, you only need to adjust the module which will handle this.

Not sure whether this is an official design pattern with an official name, but that is how I would handle this

Upvotes: 3

Related Questions