I try to apply the strategy design pattern for parsing of some textual content where each result is represented in different class.
Minimal example.
So my interface looks like this:
public interface IParseStrategy
{
object Parse(string filePath);
}
The classes that implement the algorithm:
class ParseA : IParseStrategy
{
public object Parse(string filePath) => new ConcurrentQueue<ParseAData>();
}
class ParseB : IParseStrategy
{
public object Parse(string filePath) => new Dictionary<string, ParseBData>();
}
The specific "Data" classes:
class ParseAData
{
public int Id { get; set; }
public string Name { get; set; }
}
class ParseBData
{
private byte[] data;
public byte[] GetData()
{
return data;
}
public void SetData(byte[] value)
{
data = value;
}
}
The context class that defines the interface of interests for the clients:
class Context
{
private IParseStrategy _strategy;
private void SetParsingStrategy(IParseStrategy parseStrategy)
{
_strategy = parseStrategy;
}
public object TryParse(string filePath, TypeToParse typeToParse)
{
object parsedContent = new object();
try
{
switch (typeToParse)
{
case TypeToParse.A:
SetParsingStrategy(new ParseA());
parsedContent = _strategy.Parse(filePath);
break;
case TypeToParse.B:
SetParsingStrategy(new ParseB());
parsedContent = _strategy.Parse(filePath);
break;
throw new ArgumentOutOfRangeException(nameof(typeToParse), "Uknown type to parse has been provided!");
}
}
catch (Exception)
{
throw;
}
return parsedContent;
}
}
The enum where the client can choose the right algorithm
public enum TypeToParse { A, B }
and finally the main method:
static void Main(string[] args)
{
var context = new Context();
ConcurrentQueue<ParseAData> contentOfA = (ConcurrentQueue<ParseAData>)context.TryParse("file1.whatever", TypeToParse.A);
Dictionary<string, ParseBData>contentOfB = (Dictionary<string, ParseBData>)context.TryParse("file2.whatever", TypeToParse.B);
}
So, my problem here is that the client has to know the classes in order to cast the return type object.
How to rewrite this to a more generic way, so that the compiler would infer the types automatically by using the var keyword, so the call would look like:
var contentOfA = context.TryParse("file1.whatever", TypeToParse.A);
var contentOfB = context.TryParse("file2.whatever", TypeToParse.B);
with the yellow marked types infered:

