There is an application code in which you need to dynamically determine the type of file (HTML or TXT) by content and, depending on the type of file received, call the appropriate processing algorithm.
interface IFileType { void Process(); } class HtmlFile : IFileType { public void Process() { Console.WriteLine("HTML"); } } class TxtFile : IFileType { public void Process() { Console.WriteLine("TXT"); } } class FileTypeHandler { public static IFileType Define(string fileContent) { var file = fileContent.IndexOf("<html"); if (file != -1) { return new HtmlFile(); } else { return new TxtFile(); } } } class FileProcessor { public void ProcessFile(string fileName) { StreamReader fileStream = new StreamReader(File.OpenRead(fileName)); string fileContent = fileStream.ReadToEnd(); fileStream.Close(); var fileType = FileTypeHandler.Define(fileContent); fileType.Process(); } } class Program { static void Main(string[] args) { FileProcessor fileProcessor = new FileProcessor(); fileProcessor.ProcessFile(@"d:\index.html"); Console.ReadKey(); } } Conclusion:
HTML
Everything works as it should. I am interested in how flexible my code is to the appearance of new types of files in the future , for example JSON. After all, with the advent of the new class implementing the IFileType interface, the algorithm for determining the type of the content in the class IFileType will also change .
Have I designed everything correctly, regarding the principle of openness / closeness?
FileProcessorthat his changes are not forced to change the code in theProcessFile()method of the classFileProcessor. - Adam