I am creating a instant chat application using RMI. The server sends through certain objects which I need the client to handle.
For example the server will send a JoinedGroupOperation class. In my client application I need to recognise the class and let my handler take over (HandleJoinedGroupOperation). This class will do a bunch of stuff on the client side.
My question is how can I handle classes that come from the server so I don’t need to do any if statements? ie
if(server.getResponse() instanceof JoinedGroupOperation){
HandleJoinedGroupOperation handle = new HandleJoinedGroupOperation();
handle.foo();
}
One of the possible option in your case is to use chain of responsibility design patern.
You should create some abstraction of your possible handlers(like
HandleJoinedGroupOperation), then link those handlers(preferebly at start time). As a example, create an interfacewhere
Operationis also a basic type for all possible operations. This type(Operation) can contain a field of enum type OperationType:Then in the concrete handlers you can simply check this field(although it will contain
ifstatement, but those statements will be encapsulated in each specific handler)As a simple example, here is a default implementation of a handler
In this case your
server.getResponse()method simply will return basic type ofOperationhierarchyAlso read the article to get more information