I think you really need a Factory. A Factory is a class that knows, given some information for work, how to create the necessary objects of the required type. In your case, you must create the analyzer interface, and then separate classes that implement various parsers. Finally, create a Factory parser that, given some ability to determine which type of parser to create, creates and returns the desired look. This is where your logic will be. Factory provides a way to localize the creation logic for created items.
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 plug-in model and, if necessary, Factory can be adapted to read the plug-in configuration, load the appropriate plug-ins, and create instance types as needed. In this case, it would be more appropriate to think of Factory as a “manager," because it does not just create instances.
source share