1

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?

3
  • 1
    Seems you are exploring the Visitor pattern, correct? Commented Dec 9, 2011 at 19:59
  • I am not familiar with that one yet but Ill read on it now. Commented Dec 9, 2011 at 20:24
  • maybe this can help: stackoverflow.com/questions/3672091/dispatch-design-pattern Commented Dec 9, 2011 at 22:23

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ok thanks I will look how this would work with my application!
It turned out that this works just fine !(at least on the class diagram:P). I checked Chain of Responsibility pattern too but the solution using a List is better. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.