Pattern to replace switch statement..

I have a class which processes XML data . The class hierarchy is given below

public abstract class Processor{

public abstract void buildDataFromXml();

public void publishResponse(){

StringBuffer response = new StringBuffer();

response.append("Some Common Info -- ");

response.append(buildResponse()); // Sub Classes implement this method

}

public abstract void buildResponse();

}

public class MyProcessor extends Processor{

String xmlData;

String name;

String age

String companyId;

int caseType;

public void buildDataFromXml(){

// Set the name, age and companyId,caseType from the xmlData

}

public String buildResponse(){

switch(caseType ){

case 1: // Do something and break

case 2: // Do something else and break

}

return response;

}

}

I have XML Data coming with every request, which gets processed by the appropriate processor based on the request case.

One or more requests use the same processor, since the incoming data for these requests is common but the response sent out varies in each case.

Right now, I'm using a switch statement to determine the response, but i would like to change this and not depend on switch statement. So that i can add more cases(Case 3, Case 4..) without having to go back and add more cases to switch statement everytime.

I'm unable to figure out how to do this.. Please pitch in suggestions..

[1523 byte] By [katriyaa] at [2007-10-2 9:45:05]
# 1
use a map that matches caseType/response pairs ?
Torajiroua at 2007-7-16 23:50:37 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
Hi,The Pattern which allow to avoid switch statement could be :The stategy Pattern and the State pattern.You can adapt them for your case.Regards,Sebastien Degardin.
sdegardina at 2007-7-16 23:50:37 > top of Java-index,Other Topics,Patterns & OO Design...
# 3

The code for building the response could go in a class called ResponseType. This object is passed as an argument to the buildResponse() method.

public abstract interface ResponseType {

public String buildResponse();

}

public class Processor {

...

public String buildResponse(ResponseType r) {

return r.buildResponse();

}

}

When the need for a new case (response type) comes, all you need to do is create a new implementation of ResponseType. And you will not have to change any code in Processor.

Master_Consultanta at 2007-7-16 23:50:37 > top of Java-index,Other Topics,Patterns & OO Design...