I'm trying to see if I understand depedency injection.
I have a project that is used as a parser. It can parse delimited text, key-value and will also regex.
The first way this was done was in one function with a switch. The next way was to put it in seperate functions and call it based on a switch
The next way I was thinking was to create an interface and than implement a class for each type. Is that to much work? Does the question come down to function or will doing this show benefits that I don't see yet.
I believe my problems stems that I was initially going to implement an interface and than for each time I needed a different parsing implement a new class. But than that would still require me going in and adding that to some type of logic flow as I don't see how to do that with injection frameworks.
So say I add in another way to parse that is based on tags or xml. Create the class implementing the interfaces and than I would need to add them to the flow logic to instantiate them as that interface if a user chooses to parse that type of text. Any clearner way to do that?
I think what you're really needing is a Factory. A Factory is a class that knows, given some information to work on, how to create objects of the proper type necessary. In your case, You'd create a parser interface, then separate classes implementing various parsers. Finally, create a parser factory that, given some ability to tell which kind of parser to create, creates and returns the kind needed. This is where your logic would go. The Factory provides a way to localize the creational logic for the items being created.
public interface IParser<T>
{
T Parse<T>( string item );
}
public class KeyValueParser : IParser<KeyValue>
{
KeyValuePair Parse<KeyValue>( string item );
}
...
public class ParserFactory
{
public IParser<T> CreateParser<T>()
{
var type = typeof(T);
if (type == typeof(KeyValuePair))
{
return new KeyValueParser();
}
...
throw new InvalidOperationException( "No matching parser type." );
}
}
Some others have suggested a plugin model and, if appropriate, the factory can be adapted to read a plugin configuration, load the appropriate plugins, and create the instance types as needed. In that case it might be more appropriate to think of the factory as a "manager" since it does more than simply create instances.
I would say you on right track, but you are a little wrong. You should go in direction of Factory Method and Visitor patern, to solve parsing issue first.
This work might be interesting for you - http://www.exciton.cs.rice.edu/research/sigcse05/dp4rdp.pdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With