mercredi 9 mai 2018

C# generic factory pattern without stating the type of generic

I am working on a C# project to parse files of different kinds. In order to do this, I have created the following kind of class structure:

interface FileType {}
    class FileType1 : FileType {}
    class FileType2 : FileType {}

abstract class FileProcessor<T> {}
    class Processor_FileType1 : FileProcessor<FileType1> {} 
    class Processor_FileType2 : FileProcessor<FileType2> {} 

Now, I would like to create a factory pattern that simply takes the path to the file and based upon the contents of the file decides which of the 2 processors to instantiate.

Ideally (and I know this code doesn't work), I'd want my code to look something as follows:

class ProcessorFactory
{
    public FileProcessor Create(string pathToFile)
    {
        using (var sr = pathToFile.OpenText())
        {
            var firstLine = sr.ReadLine().ToUpper();

            if (firstLine.Contains("FIELD_A"))
                return new Processor_FileType1();

            if (firstLine.Contains("FIELD_Y"))
                return new Processor_FileType2();
        }
    }
}

The issue being the compiler error Using the generic type 'FileProcessor<T>' requires 1 type arguments so my program could do something like:

public DoWork()
{
    string pathToFile = "C:/path to my file.txt";
    var processor = ProcessorFactory.Create(pathToFile);
}

and the processor variable wold be either a Processor_FileType1 or Processor_FileType2.

I know I could do it by changing the Create to take a type argument, but I'm hoping I won't have to since then it kills the idea of figuring it out based upon the data in the file.

Any ideas?





Aucun commentaire:

Enregistrer un commentaire