views:

54

answers:

3

I have a MessageProcessor class which processes xml messages of different types. A switch statement (C#) based on the message type calls the appropriate method to parse the xml and extract the data required for the type of message.

I would rather have a number of parser classes, one of which will be injected into the MessageProcessor when it is created based on the message type. Switch replaced with polymorphism - so far so good.

However, the problem I have is that the current parser methods each return different results, e.g. ParseExecute(xml, out Session), ParseCallback(xml, out id, out name, ...)

Is it possible to do what I want to do in this scenario?

+1  A: 

Just a suggestion.

Had you think about create a base result class and derive all different result types from it? Doing in that way you can think in use polymorphism to re-interpret the result to the concrete type.

But as I don't know your design in depth this can add some extra complexity for you. At least hope it can give some inspiration :)

Andres
+1, a good advice
alexm
A: 

Switch also could be replaced with ChainOfResonsibility

alexm
A: 

Some kind of factory pattern maybe

public class ParserFactory
    {
        public static IParser Create(string type)
        {
            IParser parser;
            switch (type)
            {
                case "1":
                    parser = new Parser1();
                    break;
                case "2":
                    parser = new Parser2();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("type");
            }

            return parser;
        }
    }

And return objects that implements an interface as well

public class Parser1 : IParser
    {

        public IParseResult Parse(string xml)
        {
            //Set values

            return result;
        }
    }
magnus