I have created a solution to read/process various kinds of files, e.g. XML, JSON, txt.
public interface IFileProcessor
{
TOutput Process<TInput, TOutput>(TInput input);
}
public abstract class FileProcessorBase
{
protected readonly FileInfo fileInfo;
protected FileProcessorBase(FileInfo fileInfo)
{
this.fileInfo = fileInfo;
}
protected abstract TOutput Load<TOutput>();
}
And the concrete class as follows.
public class JsonFileProcessor : FileProcessorBase, IFileProcessor
{
public JsonFileProcessor(FileInfo fileInfo) : base(fileInfo)
{
}
public TOutput Process<TInput, TOutput>(TInput from)
{
//Call Load Method
Load<string>();
}
protected override TOutput Load<TOutput>()
{
string res = "JSON Load method";
return (TOutput)Convert.ChangeType(res, typeof(TOutput), CultureInfo.InvariantCulture);
}
}
and now this is factory class
public class FileProcessorFactory
{
static readonly Dictionary<string, IFileProcessor> fileProcessor;
static FileProcessorFactory()
{
fileProcessor = new Dictionary<string, IFileProcessor>();
fileProcessor.Add("XML", new XMLFileProcessor(new FileInfo(""));
fileProcessor.Add("JSON", new JsonFileProcessor(new FileInfo(""));
}
public static IFileProcessor GetFileProcessor(string key)
{
return fileProcessor[key];
}
}
Below is FileProcessorService class
public class FileProcessorService
{
IFileProcessor fileProcessor;
public FileProcessorService(IFileProcessor fileProcessor)
{
this.fileProcessor = fileProcessor;
}
public TOutput Process<TInput, TOutput>(TInput from)
{
return fileProcessor.Process<TInput, TOutput>(from);
}
}
Now Finally, I'm calling through this way.
IFileProcessor fileProcessor = FileProcessorFactory.GetFileProcessor("XML");
FileProcessorService fileProcessorService = new FileProcessorService(fileProcessor);
var XMLResult = fileProcessorService.Process<string, string>("");
Can I use base class in strategy pattern?
Aucun commentaire:
Enregistrer un commentaire