• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

Patterns for replacing Switching statements

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class which processes XML data . The class hierarchy is given below



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..
 
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create different classes for creating different responses.

For example, your MyProcessor class (or the Processor class) will look like



All the classes you created to build different types of responses, will implement the ResponseBuilder interface.



This way, all you need to do in the MyProcessor class is


Of course, you need to set the corresponding response builder object, before making a call. It can be through the constructor, or a setter method, or even from a lookup table



In case if you haven't figured it out yet, this is Strategy pattern
 
It is difficult to free fools from the chains they revere - Voltaire. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic